blob: b820a2ba015a90050429aea697875b9cdb2780c2 [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;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070038import static android.os.Process.INVALID_UID;
39import static android.system.OsConstants.IPPROTO_TCP;
40import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060041
Hugo Benichia0385682017-03-22 17:07:57 +090042import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060043
Wenchao Tongf5ea3402015-03-04 13:26:38 -080044import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080045import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090046import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070047import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.ContentResolver;
50import android.content.Context;
51import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070052import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070053import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070054import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070055import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090057import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050059import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080060import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050061import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070062import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.INetworkPolicyListener;
64import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070065import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080066import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070067import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010068import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070069import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070070import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070072import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070074import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070075import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090076import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070077import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070078import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070079import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070080import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070081import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000082import android.net.NetworkWatchlistManager;
Jason Monk207900c2014-04-25 15:00:09 -040083import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070084import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040085import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040086import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060087import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090088import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090089import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070090import android.net.netlink.InetDiagMessage;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090091import android.net.util.MultinetworkPolicyTracker;
Luke Huang674660f2018-09-27 19:33:11 +080092import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080094import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070095import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040096import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070098import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700100import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Looper;
102import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700103import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700104import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900105import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700106import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700107import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700108import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800109import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900110import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900111import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700112import android.os.ShellCallback;
113import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900114import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700115import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400116import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700118import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700119import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700120import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700121import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900122import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700123import android.util.LocalLog;
124import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600125import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800126import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700127import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500128import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700129import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Wink Savilleab9321d2013-06-29 21:10:57 -0700132import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400133import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400134import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700135import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700136import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700137import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800138import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700139import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900140import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700141import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600142import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700143import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900144import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900145import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700146import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700147import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400148import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900149import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900150import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500151import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900152import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900153import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100154import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700155import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900156import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700157import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600158import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400159import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900160import com.android.server.connectivity.NetworkNotificationManager;
161import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700162import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900163import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800164import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700165import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100166import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500167import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700168import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700169import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900170import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700171import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600172
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700173import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700174
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700175import org.xmlpull.v1.XmlPullParser;
176import org.xmlpull.v1.XmlPullParserException;
177
178import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700180import java.io.FileNotFoundException;
181import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700182import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700184import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700185import java.net.InetAddress;
186import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700187import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700189import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700190import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900191import java.util.Comparator;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700192import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700193import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700194import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700195import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700196import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900197import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600198import java.util.SortedSet;
199import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201/**
202 * @hide
203 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800204public class ConnectivityService extends IConnectivityManager.Stub
205 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900206 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Chalard Jean4133a122018-06-04 13:33:12 +0900208 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900209 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900210 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900211 private static final String NETWORK_ARG = "networks";
212 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900213
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900214 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700215 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900217 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700218
Jeff Sharkey899223b2012-08-04 15:24:58 -0700219 // TODO: create better separation between radio types and network types
220
Robert Greenwalt42acef32009-08-12 16:08:25 -0700221 // how long to wait before switching back to a radio's default network
222 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
223 // system property that can override the above value
224 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
225 "android.telephony.apn-restore";
226
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900227 // How long to wait before putting up a "This network doesn't have an Internet connection,
228 // connect anyway?" dialog after the user selects a network that doesn't validate.
229 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
230
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900231 // Default to 30s linger time-out. Modifiable only for testing.
232 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
233 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
234 @VisibleForTesting
235 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
236
Jeremy Joslin79294842014-12-03 17:15:28 -0800237 // How long to delay to removal of a pending intent based request.
238 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
239 private final int mReleasePendingIntentDelayMs;
240
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900241 private MockableSystemProperties mSystemProperties;
242
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800243 private Tethering mTethering;
244
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700245 private final PermissionMonitor mPermissionMonitor;
246
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700247 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700248
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900249 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700250 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900251 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700252
Hugo Benichi69744342017-11-27 10:57:16 +0900253 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
254 // a direct call to LockdownVpnTracker.isEnabled().
255 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700256 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900257 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700258 private LockdownVpnTracker mLockdownTracker;
259
Erik Klineda4bfa82015-04-30 12:58:40 +0900260 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700261 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700262 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263
Luke Huang4e25ec62018-09-27 16:58:23 +0800264 private INetworkManagementService mNMS;
Luke Huang674660f2018-09-27 19:33:11 +0800265 private INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800266 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700267 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900268 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700269
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700270 private String mCurrentTcpBufferSizes;
271
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900272 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900273 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
274 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900275
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400277 // Tear down networks that have no chance (e.g. even if validated) of becoming
278 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500279 // all networks have been rematched against all NetworkRequests.
280 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400281 // Don't reap networks. This should be passed when some networks have not yet been
282 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500283 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900284 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500285
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900286 private enum UnneededFor {
287 LINGER, // Determine whether this network is unneeded and should be lingered.
288 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
289 }
290
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700291 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700293 * from one net to another. Clear happens when we get a new
294 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
295 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700296 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700297 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700298
Robert Greenwalt434203a2010-10-11 16:00:27 -0700299 /**
300 * used internally to reload global proxy settings
301 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700302 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700303
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700304 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400305 * PAC manager has received new port.
306 */
307 private static final int EVENT_PROXY_HAS_CHANGED = 16;
308
Robert Greenwalte049c232014-04-11 15:53:27 -0700309 /**
310 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700311 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700312 */
313 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
314
Robert Greenwalt7b816022014-04-18 15:25:25 -0700315 /**
316 * used internally when registering NetworkAgents
317 * obj = Messenger
318 */
319 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
320
Robert Greenwalt9258c642014-03-26 16:47:06 -0700321 /**
322 * used to add a network request
323 * includes a NetworkRequestInfo
324 */
325 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
326
327 /**
328 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900329 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700330 * cancel it.
331 * includes a NetworkRequestInfo
332 */
333 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
334
335 /**
336 * used to add a network listener - no request
337 * includes a NetworkRequestInfo
338 */
339 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
340
341 /**
342 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400343 * arg1 = UID of caller
344 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700345 */
346 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
347
Robert Greenwalta67be032014-05-16 15:49:14 -0700348 /**
349 * used internally when registering NetworkFactories
350 * obj = Messenger
351 */
352 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
353
Robert Greenwalt27711812014-06-25 16:45:57 -0700354 /**
355 * used internally to expire a wakelock when transitioning
356 * from one net to another. Expire happens when we fail to find
357 * a new network (typically after 1 minute) -
358 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
359 * a replacement network.
360 */
361 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
362
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700363 /**
364 * Used internally to indicate the system is ready.
365 */
366 private static final int EVENT_SYSTEM_READY = 25;
367
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800368 /**
369 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400370 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800371 */
372 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
373
374 /**
375 * used to remove a pending intent and its associated network request.
376 * arg1 = UID of caller
377 * obj = PendingIntent
378 */
379 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
380
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900381 /**
382 * used to specify whether a network should be used even if unvalidated.
383 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
384 * arg2 = whether to remember this choice in the future (1 or 0)
385 * obj = network
386 */
387 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
388
389 /**
390 * used to ask the user to confirm a connection to an unvalidated network.
391 * obj = network
392 */
393 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700394
Erik Klineda4bfa82015-04-30 12:58:40 +0900395 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700396 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900397 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700398 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900399
Paul Jensen694f2b82015-06-17 14:15:39 -0400400 /**
401 * used to add a network listener with a pending intent
402 * obj = NetworkRequestInfo
403 */
404 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
405
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900406 /**
407 * used to specify whether a network should not be penalized when it becomes unvalidated.
408 */
409 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
410
411 /**
412 * used to trigger revalidation of a network.
413 */
414 private static final int EVENT_REVALIDATE_NETWORK = 36;
415
Erik Klinea24d4592018-01-11 21:07:29 +0900416 // Handle changes in Private DNS settings.
417 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
418
dalyk7301aa42018-03-05 12:42:22 -0500419 // Handle private DNS validation status updates.
420 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
421
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900422 private static String eventName(int what) {
423 return sMagicDecoderRing.get(what, Integer.toString(what));
424 }
425
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900426 /** Handler thread used for both of the handlers below. */
427 @VisibleForTesting
428 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700429 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700430 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700431 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700432 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900433 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700434
Mike Lockwood0f79b542009-08-14 14:18:49 -0400435 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800436 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400437
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700438 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700439 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800440 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700441
Chalard Jean52c2aa72018-06-07 16:44:04 +0900442 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
443 // the world when it changes.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900444 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400445
Erik Klineda4bfa82015-04-30 12:58:40 +0900446 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700447
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400448 private UserManager mUserManager;
449
Chalard Jean4133a122018-06-04 13:33:12 +0900450 private NetworkConfig[] mNetConfigs;
451 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700452
Robert Greenwalt50393202011-06-21 17:26:14 -0700453 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900454 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700455
Chalard Jean4133a122018-06-04 13:33:12 +0900456 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400457
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900458 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900459 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900460 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900461
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700462 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800463 private static final int MIN_NET_ID = 100; // some reserved marks
464 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700465 private int mNextNetId = MIN_NET_ID;
466
Robert Greenwalt34524f02014-05-18 16:22:10 -0700467 // sequence number of NetworkRequests
468 private int mNextNetworkRequestId = 1;
469
Erik Kline7523eb32015-07-09 18:24:03 +0900470 // NetworkRequest activity String log entries.
471 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
472 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
473
Hugo Benichic2ae2872016-07-11 11:05:12 +0900474 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900475 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900476 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
477
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900478 private static final int MAX_WAKELOCK_LOGS = 20;
479 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900480 private int mTotalWakelockAcquisitions = 0;
481 private int mTotalWakelockReleases = 0;
482 private long mTotalWakelockDurationMs = 0;
483 private long mMaxWakelockDurationMs = 0;
484 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900485
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700486 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
487 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 private static class ValidationLog {
489 final Network mNetwork;
Chalard Jeand771aa02018-04-26 16:16:10 +0900490 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700492
Chalard Jeand771aa02018-04-26 16:16:10 +0900493 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400494 mNetwork = network;
Chalard Jeand771aa02018-04-26 16:16:10 +0900495 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400496 mLog = log;
497 }
498 }
Chalard Jean4133a122018-06-04 13:33:12 +0900499 private final ArrayDeque<ValidationLog> mValidationLogs = new ArrayDeque<>(MAX_VALIDATION_LOGS);
Paul Jensen0808eb82016-06-03 13:51:21 -0400500
Chalard Jeand771aa02018-04-26 16:16:10 +0900501 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900502 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
504 mValidationLogs.removeLast();
505 }
Chalard Jeand771aa02018-04-26 16:16:10 +0900506 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700507 }
508 }
509
Hugo Benichif9fdf872016-07-28 17:53:06 +0900510 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900511
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700512 @GuardedBy("mBandwidthRequests")
513 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
514
Erik Kline065ab6e2016-10-02 18:02:14 +0900515 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900516 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900517
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900518 @VisibleForTesting
519 final MultipathPolicyTracker mMultipathPolicyTracker;
520
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521 /**
522 * Implements support for the legacy "one network per network type" model.
523 *
524 * We used to have a static array of NetworkStateTrackers, one for each
525 * network type, but that doesn't work any more now that we can have,
526 * for example, more that one wifi network. This class stores all the
527 * NetworkAgentInfo objects that support a given type, but the legacy
528 * API will only see the first one.
529 *
530 * It serves two main purposes:
531 *
532 * 1. Provide information about "the network for a given type" (since this
533 * API only supports one).
534 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
535 * the first network for a given type changes, or if the default network
536 * changes.
537 */
538 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900539
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900540 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900541 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700543 /**
544 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
545 * Each list holds references to all NetworkAgentInfos that are used to
546 * satisfy requests for that network type.
547 *
548 * This array is built out at startup such that an unsupported network
549 * doesn't get an ArrayList instance, making this a tristate:
550 * unsupported, supported but not active and active.
551 *
552 * The actual lists are populated when we scan the network types that
553 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900554 *
555 * Threading model:
556 * - addSupportedType() is only called in the constructor
557 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
558 * They are therefore not thread-safe with respect to each other.
559 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
560 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
561 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564
565 public LegacyTypeTracker() {
566 mTypeLists = (ArrayList<NetworkAgentInfo>[])
567 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
568 }
569
570 public void addSupportedType(int type) {
571 if (mTypeLists[type] != null) {
572 throw new IllegalStateException(
573 "legacy list for type " + type + "already initialized");
574 }
Chalard Jean4133a122018-06-04 13:33:12 +0900575 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 }
577
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700578 public boolean isTypeSupported(int type) {
579 return isNetworkTypeValid(type) && mTypeLists[type] != null;
580 }
581
582 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900583 synchronized (mTypeLists) {
584 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
585 return mTypeLists[type].get(0);
586 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900588 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700589 }
590
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900592 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900593 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700594 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 }
598 }
599
600 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700601 public void add(int type, NetworkAgentInfo nai) {
602 if (!isTypeSupported(type)) {
603 return; // Invalid network type.
604 }
605 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
606
607 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
608 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700609 return;
610 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900611 synchronized (mTypeLists) {
612 list.add(nai);
613 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900614
615 // 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 +0900616 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900617 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700618 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
619 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700620 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700621 }
622
Lorenzo Colittia793a672014-07-31 23:20:17 +0900623 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900624 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
626 if (list == null || list.isEmpty()) {
627 return;
628 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900630
Hugo Benichi78caa2582016-06-21 09:48:07 +0900631 synchronized (mTypeLists) {
632 if (!list.remove(nai)) {
633 return;
634 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900635 }
636
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 final DetailedState state = DetailedState.DISCONNECTED;
638
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700640 maybeLogBroadcast(nai, state, type, wasDefault);
641 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900642 }
643
644 if (!list.isEmpty() && wasFirstNetwork) {
645 if (DBG) log("Other network available for type " + type +
646 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900647 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
649 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900650 }
651 }
652
653 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900654 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
655 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700656 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900657 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700658 }
659 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700660
Robert Greenwalt8d482522015-06-24 13:23:42 -0700661 // send out another legacy broadcast - currently only used for suspend/unsuspend
662 // toggle
663 public void update(NetworkAgentInfo nai) {
664 final boolean isDefault = isDefaultNetwork(nai);
665 final DetailedState state = nai.networkInfo.getDetailedState();
666 for (int type = 0; type < mTypeLists.length; type++) {
667 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700668 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900669 final boolean isFirst = contains && (nai == list.get(0));
670 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700671 maybeLogBroadcast(nai, state, type, isDefault);
672 sendLegacyNetworkBroadcast(nai, state, type);
673 }
674 }
675 }
676
Lorenzo Colittia793a672014-07-31 23:20:17 +0900677 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900678 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900679 String state = (nai.networkInfo != null) ?
680 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
681 "???/???";
682 return name + " " + state;
683 }
684
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700685 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900686 pw.println("mLegacyTypeTracker:");
687 pw.increaseIndent();
688 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700689 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900690 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700691 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900692 pw.println();
693 pw.println("Current state:");
694 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900695 synchronized (mTypeLists) {
696 for (int type = 0; type < mTypeLists.length; type++) {
697 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
698 for (NetworkAgentInfo nai : mTypeLists[type]) {
699 pw.println(type + " " + naiToString(nai));
700 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900701 }
702 }
703 pw.decreaseIndent();
704 pw.decreaseIndent();
705 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700706 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700707 }
708 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
709
Vishnu Nair5c010902017-10-26 10:08:50 -0700710 /**
711 * Helper class which parses out priority arguments and dumps sections according to their
712 * priority. If priority arguments are omitted, function calls the legacy dump command.
713 */
714 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
715 @Override
716 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
717 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
718 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
719 }
720
721 @Override
722 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
723 doDump(fd, pw, args, asProto);
724 }
725
726 @Override
727 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
728 doDump(fd, pw, args, asProto);
729 }
730 };
731
Jeff Sharkey899223b2012-08-04 15:24:58 -0700732 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700733 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900734 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
735 }
736
737 @VisibleForTesting
738 protected ConnectivityService(Context context, INetworkManagementService netManager,
739 INetworkStatsService statsService, INetworkPolicyManager policyManager,
740 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800741 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800742
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900743 mSystemProperties = getSystemProperties();
744
Hugo Benichif9fdf872016-07-28 17:53:06 +0900745 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900746 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900747 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900748 mNetworkRequests.put(mDefaultRequest, defaultNRI);
749 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900750
Chalard Jeandda156a2018-01-10 21:19:32 +0900751 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900752 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700753
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700754 // The default WiFi request is a background request so that apps using WiFi are
755 // migrated to a better network (typically ethernet) when one comes up, instead
756 // of staying on WiFi forever.
757 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
758 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
759
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900760 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900761 mHandlerThread.start();
762 mHandler = new InternalHandler(mHandlerThread.getLooper());
763 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700764
Jeremy Joslin79294842014-12-03 17:15:28 -0800765 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
766 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
767
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900768 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900769
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700770 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800771 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800772 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900774 mPolicyManagerInternal = checkNotNull(
775 LocalServices.getService(NetworkPolicyManagerInternal.class),
776 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900777 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900778
Luke Huang674660f2018-09-27 19:33:11 +0800779 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700780 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700781 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700782
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700783 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900784 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700785 } catch (RemoteException e) {
786 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700787 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700788 }
789
790 final PowerManager powerManager = (PowerManager) context.getSystemService(
791 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700792 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
793 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
794 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800795 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700796
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700797 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700798
Wink Saville51f456f2013-04-23 14:26:51 -0700799 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900800 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700801 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700802 String[] naStrings = context.getResources().getStringArray(
803 com.android.internal.R.array.networkAttributes);
804 for (String naString : naStrings) {
805 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700806 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700807 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700808 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800809 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700810 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700811 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700812 }
Wink Saville51f456f2013-04-23 14:26:51 -0700813 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
814 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
815 n.type);
816 continue;
817 }
Wink Saville975c8482011-04-07 14:23:45 -0700818 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800819 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700820 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700821 continue;
822 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700823 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700824
Wink Saville975c8482011-04-07 14:23:45 -0700825 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700826 mNetworksDefined++;
827 } catch(Exception e) {
828 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700829 }
830 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700831
832 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
833 if (mNetConfigs[TYPE_VPN] == null) {
834 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
835 // don't need to add TYPE_VPN to mNetConfigs.
836 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
837 mNetworksDefined++; // used only in the log() statement below.
838 }
839
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900840 // Do the same for Ethernet, since it's often not specified in the configs, although many
841 // devices can use it via USB host adapters.
842 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
843 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
844 mNetworksDefined++;
845 }
846
Wink Saville5e56bc52013-07-29 15:00:57 -0700847 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700848
Robert Greenwalt50393202011-06-21 17:26:14 -0700849 mProtectedNetworks = new ArrayList<Integer>();
850 int[] protectedNetworks = context.getResources().getIntArray(
851 com.android.internal.R.array.config_protectedNetworks);
852 for (int p : protectedNetworks) {
853 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
854 mProtectedNetworks.add(p);
855 } else {
856 if (DBG) loge("Ignoring protectedNetwork " + p);
857 }
858 }
859
Erik Kline47222fc2017-04-30 19:36:15 +0900860 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800861
Luke Huang4e25ec62018-09-27 16:58:23 +0800862 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700863
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700864 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700865 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100866 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700867 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700868 intentFilter.addAction(Intent.ACTION_USER_ADDED);
869 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000870 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700871 mContext.registerReceiverAsUser(
872 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000873 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
874 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900875
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700876 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800877 mNMS.registerObserver(mTethering);
878 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700879 } catch (RemoteException e) {
880 loge("Error registering observer :" + e);
881 }
882
Erik Klineda4bfa82015-04-30 12:58:40 +0900883 mSettingsObserver = new SettingsObserver(mContext, mHandler);
884 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800885
Chalard Jean4133a122018-06-04 13:33:12 +0900886 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
887 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400888
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400889 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900890
891 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900892 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
893 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900894
895 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
896 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
897 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
898 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
899 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
900 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
901 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900902
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900903 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900904 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900905 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900906
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900907 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
908
Luke Huang4e25ec62018-09-27 16:58:23 +0800909 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900910 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700912
Erik Kline47222fc2017-04-30 19:36:15 +0900913 private Tethering makeTethering() {
914 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900915 final TetheringDependencies deps = new TetheringDependencies() {
916 @Override
917 public boolean isTetheringSupported() {
918 return ConnectivityService.this.isTetheringSupported();
919 }
Erik Kline72302902018-06-14 17:36:40 +0900920 @Override
921 public NetworkRequest getDefaultNetworkRequest() {
922 return mDefaultRequest;
923 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900924 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800925 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900926 IoThread.get().getLooper(), new MockableSystemProperties(),
927 deps);
928 }
929
Chalard Jean26400492018-04-18 20:18:38 +0900930 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
931 final NetworkCapabilities netCap = new NetworkCapabilities();
932 netCap.addCapability(NET_CAPABILITY_INTERNET);
933 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
934 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
935 netCap.setSingleUid(uid);
936 return netCap;
937 }
938
Chalard Jeandda156a2018-01-10 21:19:32 +0900939 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900940 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900941 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900942 netCap.addCapability(NET_CAPABILITY_INTERNET);
943 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900944 if (transportType > -1) {
945 netCap.addTransportType(transportType);
946 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900947 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900948 }
949
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900950 // Used only for testing.
951 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700952 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900953 // changing ContentResolver to make registerContentObserver non-final).
954 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
955 // by subclassing SettingsObserver.
956 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700957 void updateAlwaysOnNetworks() {
958 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900959 }
960
Erik Kline736353a2018-03-21 07:18:33 -0700961 // See FakeSettingsProvider comment above.
962 @VisibleForTesting
963 void updatePrivateDnsSettings() {
964 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
965 }
966
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700967 private void handleAlwaysOnNetworkRequest(
968 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900969 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700970 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
971 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +0900972 if (enable == isEnabled) {
973 return; // Nothing to do.
974 }
975
976 if (enable) {
977 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700978 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900979 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700980 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +0900981 }
982 }
983
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700984 private void handleConfigureAlwaysOnNetworks() {
985 handleAlwaysOnNetworkRequest(
986 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
987 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
988 false);
989 }
990
Erik Klineda4bfa82015-04-30 12:58:40 +0900991 private void registerSettingsCallbacks() {
992 // Watch for global HTTP proxy changes.
993 mSettingsObserver.observe(
994 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
995 EVENT_APPLY_GLOBAL_HTTP_PROXY);
996
997 // Watch for whether or not to keep mobile data always on.
998 mSettingsObserver.observe(
999 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001000 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1001
1002 // Watch for whether or not to keep wifi always on.
1003 mSettingsObserver.observe(
1004 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1005 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001006 }
1007
Erik Klinea24d4592018-01-11 21:07:29 +09001008 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001009 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1010 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001011 }
1012 }
1013
Robert Greenwalt34524f02014-05-18 16:22:10 -07001014 private synchronized int nextNetworkRequestId() {
1015 return mNextNetworkRequestId++;
1016 }
1017
Paul Jensen67b0b072015-06-10 11:22:17 -04001018 @VisibleForTesting
1019 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001020 synchronized (mNetworkForNetId) {
1021 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1022 int netId = mNextNetId;
1023 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1024 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001025 if (!mNetIdInUse.get(netId)) {
1026 mNetIdInUse.put(netId, true);
1027 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001028 }
1029 }
1030 }
1031 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001032 }
1033
Chalard Jeanc0982912018-06-07 16:11:34 +09001034 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001036 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1037 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001039 state = nai.getNetworkState();
1040 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001042 final NetworkInfo info = new NetworkInfo(networkType, 0,
1043 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1045 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001046 final NetworkCapabilities capabilities = new NetworkCapabilities();
1047 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1048 !info.isRoaming());
1049 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001052 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001053 return state;
1054 } else {
1055 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001056 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001057 }
1058
junyulai4a192e22018-06-13 15:00:37 +08001059 @VisibleForTesting
1060 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001061 if (network == null) {
1062 return null;
1063 }
Erik Kline736353a2018-03-21 07:18:33 -07001064 return getNetworkAgentInfoForNetId(network.netId);
1065 }
1066
1067 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001069 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001070 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001072
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001073 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001074 synchronized (mVpns) {
1075 if (!mLockdownEnabled) {
1076 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001077 Vpn vpn = mVpns.get(user);
1078 if (vpn != null && vpn.appliesToUid(uid)) {
1079 return vpn.getUnderlyingNetworks();
1080 }
1081 }
1082 }
1083 return null;
1084 }
1085
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001086 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001087 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001088
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001089 final Network[] networks = getVpnUnderlyingNetworks(uid);
1090 if (networks != null) {
1091 // getUnderlyingNetworks() returns:
1092 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1093 // empty array => the VPN explicitly said "no default network".
1094 // non-empty array => the VPN specified one or more default networks; we use the
1095 // first one.
1096 if (networks.length > 0) {
1097 nai = getNetworkAgentInfoForNetwork(networks[0]);
1098 } else {
1099 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001100 }
1101 }
1102
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001103 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001104 return nai.getNetworkState();
1105 } else {
1106 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001108 }
1109
1110 /**
1111 * Check if UID should be blocked from using the network with the given LinkProperties.
1112 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1114 boolean ignoreBlocked) {
1115 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001116 if (ignoreBlocked) {
1117 return false;
1118 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001120 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1121 if (isSystem(uid)) {
1122 return false;
1123 }
Robin Lee17e61832016-05-09 13:46:28 +01001124 synchronized (mVpns) {
1125 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1126 if (vpn != null && vpn.isBlockingUid(uid)) {
1127 return true;
1128 }
1129 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001130 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001131 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 }
1133
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001134 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001135 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1136 return;
1137 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001138 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001139 synchronized (mBlockedAppUids) {
1140 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001141 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001142 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001143 blocked = false;
1144 } else {
1145 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001146 }
1147 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001148 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1149 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1150 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001151 }
1152
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1155 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001156 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1160
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 }
Hugo Benichi69744342017-11-27 10:57:16 +09001164 synchronized (mVpns) {
1165 if (mLockdownTracker != null) {
1166 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1167 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001168 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 }
1170
1171 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 * Return NetworkInfo for the active (i.e., connected) network interface.
1173 * It is assumed that at most one network is active at a time. If more
1174 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001175 * @return the info for the active network, or {@code null} if none is
1176 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001180 enforceAccessPermission();
1181 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001183 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1185 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187
Paul Jensen31a94f42015-02-13 14:18:39 -05001188 @Override
1189 public Network getActiveNetwork() {
1190 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001192 }
1193
1194 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001195 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001196 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001197 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001198 }
1199
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001200 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001201 final int user = UserHandle.getUserId(uid);
1202 int vpnNetId = NETID_UNSET;
1203 synchronized (mVpns) {
1204 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001205 // TODO : now that capabilities contain the UID, the appliesToUid test should
1206 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001207 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1208 }
1209 NetworkAgentInfo nai;
1210 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001211 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001212 if (nai != null) {
1213 final NetworkCapabilities requiredCaps =
1214 createDefaultNetworkCapabilitiesForUid(uid);
1215 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1216 return nai.network;
1217 }
1218 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001219 }
1220 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001221 if (nai != null
1222 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1223 nai = null;
1224 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001225 return nai != null ? nai.network : null;
1226 }
1227
Lorenzo Colitti18660282016-07-04 12:55:44 +09001228 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001229 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1230 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 final int uid = Binder.getCallingUid();
1232 NetworkState state = getUnfilteredActiveNetworkState(uid);
1233 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001234 }
1235
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001236 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001237 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001238 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001239 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001240 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001241 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001242 }
1243
1244 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 public NetworkInfo getNetworkInfo(int networkType) {
1246 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001247 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001248 if (getVpnUnderlyingNetworks(uid) != null) {
1249 // A VPN is active, so we may need to return one of its underlying networks. This
1250 // information is not available in LegacyTypeTracker, so we have to get it from
1251 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001252 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001253 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001254 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001255 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001256 }
1257 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001258 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001259 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001263 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001265 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001267 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001268 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001269 return state.networkInfo;
1270 } else {
1271 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001272 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 }
1274
1275 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 public NetworkInfo[] getAllNetworkInfo() {
1277 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001278 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001279 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1280 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001281 NetworkInfo info = getNetworkInfo(networkType);
1282 if (info != null) {
1283 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001286 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
1288
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001289 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001290 public Network getNetworkForType(int networkType) {
1291 enforceAccessPermission();
1292 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001293 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001294 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001295 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001296 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001297 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001298 }
1299
1300 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 public Network[] getAllNetworks() {
1302 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001303 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001304 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001306 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001307 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001308 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001309 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001310 }
1311
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001312 @Override
1313 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1314 // The basic principle is: if an app's traffic could possibly go over a
1315 // network, without the app doing anything multinetwork-specific,
1316 // (hence, by "default"), then include that network's capabilities in
1317 // the array.
1318 //
1319 // In the normal case, app traffic only goes over the system's default
1320 // network connection, so that's the only network returned.
1321 //
1322 // With a VPN in force, some app traffic may go into the VPN, and thus
1323 // over whatever underlying networks the VPN specifies, while other app
1324 // traffic may go over the system default network (e.g.: a split-tunnel
1325 // VPN, or an app disallowed by the VPN), so the set of networks
1326 // returned includes the VPN's underlying networks and the system
1327 // default.
1328 enforceAccessPermission();
1329
Chalard Jean4133a122018-06-04 13:33:12 +09001330 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001331
1332 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001333 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001334 if (nc != null) {
1335 result.put(nai.network, nc);
1336 }
1337
Hugo Benichi69744342017-11-27 10:57:16 +09001338 synchronized (mVpns) {
1339 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001340 Vpn vpn = mVpns.get(userId);
1341 if (vpn != null) {
1342 Network[] networks = vpn.getUnderlyingNetworks();
1343 if (networks != null) {
1344 for (Network network : networks) {
1345 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001346 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001347 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001348 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001349 }
1350 }
1351 }
1352 }
1353 }
1354 }
1355
1356 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1357 out = result.values().toArray(out);
1358 return out;
1359 }
1360
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001361 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001362 public boolean isNetworkSupported(int networkType) {
1363 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001364 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001365 }
1366
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001367 /**
1368 * Return LinkProperties for the active (i.e., connected) default
1369 * network interface. It is assumed that at most one default network
1370 * is active at a time. If more than one is active, it is indeterminate
1371 * which will be returned.
1372 * @return the ip properties for the active network, or {@code null} if
1373 * none is active
1374 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001376 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001377 enforceAccessPermission();
1378 final int uid = Binder.getCallingUid();
1379 NetworkState state = getUnfilteredActiveNetworkState(uid);
1380 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001381 }
1382
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001384 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001385 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001386 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1387 if (nai != null) {
1388 synchronized (nai) {
1389 return new LinkProperties(nai.linkProperties);
1390 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001391 }
1392 return null;
1393 }
1394
Robert Greenwalt12e67352014-05-13 21:41:06 -07001395 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001396 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001397 public LinkProperties getLinkProperties(Network network) {
1398 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001399 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1400 }
1401
1402 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1403 if (nai == null) {
1404 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001405 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001406 synchronized (nai) {
1407 return new LinkProperties(nai.linkProperties);
1408 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001409 }
1410
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001411 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001412 if (nai != null) {
1413 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001414 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001415 return networkCapabilitiesRestrictedForCallerPermissions(
1416 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001417 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001418 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001419 }
1420 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001421 return null;
1422 }
1423
1424 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001425 public NetworkCapabilities getNetworkCapabilities(Network network) {
1426 enforceAccessPermission();
1427 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1428 }
1429
Chalard Jeanb03a6222018-04-11 21:09:10 +09001430 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001431 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001432 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001433 if (!checkSettingsPermission(callerPid, callerUid)) {
1434 newNc.setUids(null);
1435 newNc.setSSID(null);
1436 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001437 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001438 }
1439
Chalard Jeanb552c462018-02-21 18:43:54 +09001440 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1441 if (!checkSettingsPermission()) {
1442 nc.setSingleUid(Binder.getCallingUid());
1443 }
1444 }
1445
Chalard Jean26aa91a2018-03-20 19:13:57 +09001446 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1447 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1448 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1449 }
1450 }
1451
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001452 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001453 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001454 // Require internal since we're handing out IMSI details
1455 enforceConnectivityInternalPermission();
1456
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001457 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001458 for (Network network : getAllNetworks()) {
1459 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1460 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001461 // TODO (b/73321673) : NetworkState contains a copy of the
1462 // NetworkCapabilities, which may contain UIDs of apps to which the
1463 // network applies. Should the UIDs be cleared so as not to leak or
1464 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001465 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001466 }
1467 }
1468 return result.toArray(new NetworkState[result.size()]);
1469 }
1470
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001471 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001472 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001473 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001474 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1475 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1476 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001477 }
1478
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001479 @Override
1480 public boolean isActiveNetworkMetered() {
1481 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001482
Eric Enslenc81ef192018-02-07 18:03:53 -08001483 final int uid = Binder.getCallingUid();
1484 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001485 if (caps != null) {
1486 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1487 } else {
1488 // Always return the most conservative value
1489 return true;
1490 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001491 }
1492
Jeff Sharkey216c1812012-08-05 14:29:23 -07001493 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1494 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001495 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001496 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001497 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001498 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001499 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001500
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001501 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001502 * Ensures that the system cannot call a particular method.
1503 */
1504 private boolean disallowedBecauseSystemCaller() {
1505 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1506 // requestRouteToHost.
1507 if (isSystem(Binder.getCallingUid())) {
1508 log("This method exists only for app backwards compatibility"
1509 + " and must not be called by system services.");
1510 return true;
1511 }
1512 return false;
1513 }
1514
1515 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 * Ensure that a network route exists to deliver traffic to the specified
1517 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001518 * @param networkType the type of the network over which traffic to the
1519 * specified host is to be routed
1520 * @param hostAddress the IP address of the host to which the route is
1521 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 * @return {@code true} on success, {@code false} on failure
1523 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001524 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001525 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001526 if (disallowedBecauseSystemCaller()) {
1527 return false;
1528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001530 if (mProtectedNetworks.contains(networkType)) {
1531 enforceConnectivityInternalPermission();
1532 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001533
Chad Brubakerc0234532014-02-14 13:24:29 -08001534 InetAddress addr;
1535 try {
1536 addr = InetAddress.getByAddress(hostAddress);
1537 } catch (UnknownHostException e) {
1538 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1539 return false;
1540 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001543 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 return false;
1545 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001546
1547 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1548 if (nai == null) {
1549 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1550 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1551 } else {
1552 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1553 }
1554 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001555 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001556
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001557 DetailedState netState;
1558 synchronized (nai) {
1559 netState = nai.networkInfo.getDetailedState();
1560 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001561
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001562 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001563 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001564 log("requestRouteToHostAddress on down network "
1565 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001566 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001567 }
1568 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001570
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001571 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001572 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001573 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001574 LinkProperties lp;
1575 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001576 synchronized (nai) {
1577 lp = nai.linkProperties;
1578 netId = nai.network.netId;
1579 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001580 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001581 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1582 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001583 } finally {
1584 Binder.restoreCallingIdentity(token);
1585 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001586 }
1587
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001588 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001589 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001590 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001591 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001592 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001593 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001594 if (bestRoute.getGateway().equals(addr)) {
1595 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001596 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001597 } else {
1598 // if we will connect to this through another route, add a direct route
1599 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001600 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001601 }
1602 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001603 if (DBG) log("Adding legacy route " + bestRoute +
1604 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001605 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001606 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001607 } catch (Exception e) {
1608 // never crash - catch them all
1609 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001610 return false;
1611 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001612 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
dalyk7301aa42018-03-05 12:42:22 -05001615 @VisibleForTesting
1616 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1617 @Override
1618 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1619 String hostname, boolean validated) {
1620 try {
1621 mHandler.sendMessage(mHandler.obtainMessage(
1622 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1623 new PrivateDnsValidationUpdate(netId,
1624 InetAddress.parseNumericAddress(ipAddress),
1625 hostname, validated)));
1626 } catch (IllegalArgumentException e) {
1627 loge("Error parsing ip address in validation event");
1628 }
1629 }
1630 };
1631
1632 @VisibleForTesting
1633 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001634 final IIpConnectivityMetrics ipConnectivityMetrics =
1635 IIpConnectivityMetrics.Stub.asInterface(
1636 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1637 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001638 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001639 return;
dalyk7301aa42018-03-05 12:42:22 -05001640 }
1641
1642 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001643 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001644 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1645 mNetdEventCallback);
1646 } catch (Exception e) {
1647 loge("Error registering netd callback: " + e);
1648 }
1649 }
1650
Jeff Sharkey75d31892018-01-18 22:01:59 +09001651 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001652 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001653 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001654 // TODO: notify UID when it has requested targeted updates
1655 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001656 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001657 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001658 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001659 if (restrictBackground) {
1660 log("onRestrictBackgroundChanged(true): disabling tethering");
1661 mTethering.untetherAll();
1662 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001663 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001664 };
1665
Robin Lee3b3dd942015-05-12 18:14:58 +01001666 /**
1667 * Require that the caller is either in the same user or has appropriate permission to interact
1668 * across users.
1669 *
1670 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1671 */
1672 private void enforceCrossUserPermission(int userId) {
1673 if (userId == UserHandle.getCallingUserId()) {
1674 // Not a cross-user call.
1675 return;
1676 }
1677 mContext.enforceCallingOrSelfPermission(
1678 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1679 "ConnectivityService");
1680 }
1681
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001682 private void enforceInternetPermission() {
1683 mContext.enforceCallingOrSelfPermission(
1684 android.Manifest.permission.INTERNET,
1685 "ConnectivityService");
1686 }
1687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001689 mContext.enforceCallingOrSelfPermission(
1690 android.Manifest.permission.ACCESS_NETWORK_STATE,
1691 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
1694 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001695 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697
Charles He36738632017-05-15 17:07:18 +01001698 private void enforceSettingsPermission() {
1699 mContext.enforceCallingOrSelfPermission(
1700 android.Manifest.permission.NETWORK_SETTINGS,
1701 "ConnectivityService");
1702 }
1703
Chalard Jeanb552c462018-02-21 18:43:54 +09001704 private boolean checkSettingsPermission() {
1705 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1706 android.Manifest.permission.NETWORK_SETTINGS);
1707 }
1708
1709 private boolean checkSettingsPermission(int pid, int uid) {
1710 return PERMISSION_GRANTED == mContext.checkPermission(
1711 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1712 }
1713
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001714 private void enforceTetherAccessPermission() {
1715 mContext.enforceCallingOrSelfPermission(
1716 android.Manifest.permission.ACCESS_NETWORK_STATE,
1717 "ConnectivityService");
1718 }
1719
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001720 private void enforceConnectivityInternalPermission() {
1721 mContext.enforceCallingOrSelfPermission(
1722 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1723 "ConnectivityService");
1724 }
1725
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001726 private boolean checkNetworkStackPermission() {
1727 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1728 android.Manifest.permission.NETWORK_STACK);
1729 }
1730
Hugo Benichi514da602016-07-19 15:59:27 +09001731 private void enforceConnectivityRestrictedNetworksPermission() {
1732 try {
1733 mContext.enforceCallingOrSelfPermission(
1734 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1735 "ConnectivityService");
1736 return;
1737 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1738 enforceConnectivityInternalPermission();
1739 }
1740
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001741 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001742 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001743 }
1744
Lorenzo Colitti18660282016-07-04 12:55:44 +09001745 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001746 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001747 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001748 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001749 }
1750
1751 private void sendInetConditionBroadcast(NetworkInfo info) {
1752 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1753 }
1754
Wink Saville628b0852011-08-04 15:01:58 -07001755 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001756 synchronized (mVpns) {
1757 if (mLockdownTracker != null) {
1758 info = new NetworkInfo(info);
1759 mLockdownTracker.augmentNetworkInfo(info);
1760 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001761 }
1762
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001763 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001764 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001765 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 if (info.isFailover()) {
1767 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1768 info.setFailover(false);
1769 }
1770 if (info.getReason() != null) {
1771 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1772 }
1773 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001774 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1775 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001777 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001778 return intent;
1779 }
1780
1781 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1782 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1783 }
1784
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001785 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001786 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1787 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1788 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001789 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001790 final long ident = Binder.clearCallingIdentity();
1791 try {
1792 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1793 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1794 } finally {
1795 Binder.restoreCallingIdentity(ident);
1796 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001797 }
1798
Mike Lockwood0f79b542009-08-14 14:18:49 -04001799 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001800 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001801 if (!mSystemReady) {
1802 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001803 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001804 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001805 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001806 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001807 }
1808
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001809 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001810 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001811 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001812 final NetworkInfo ni = intent.getParcelableExtra(
1813 ConnectivityManager.EXTRA_NETWORK_INFO);
1814 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1815 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1816 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001817 } else {
1818 BroadcastOptions opts = BroadcastOptions.makeBasic();
1819 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1820 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001821 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001822 final IBatteryStats bs = BatteryStatsService.getService();
1823 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001824 bs.noteConnectivityChanged(intent.getIntExtra(
1825 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001826 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001827 } catch (RemoteException e) {
1828 }
Chad Brubakerac925012018-03-08 10:37:09 -08001829 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001830 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001831 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001832 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001833 } finally {
1834 Binder.restoreCallingIdentity(ident);
1835 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001836 }
1837 }
1838
1839 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09001840 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001841 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001842
Hugo Benichi20035e02017-04-26 14:53:28 +09001843 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001844 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001845 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001846 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001847 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001848 }
1849 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001850 // load the global proxy at startup
1851 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001852
Robin Lee244ce8e2016-01-05 18:03:46 +00001853 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1854 // for user to unlock device too.
1855 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001856
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001857 // Create network requests for always-on networks.
1858 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09001859
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001860 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001861
1862 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001866 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001867 *
1868 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001869 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001870 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001871 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1872 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001873
1874 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001875 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001876
Robert Greenwalt7b816022014-04-18 15:25:25 -07001877 if (networkAgent.networkCapabilities.hasTransport(
1878 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001879 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1880 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001881 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001882 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001883 } else if (networkAgent.networkCapabilities.hasTransport(
1884 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001885 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1886 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001887 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001888 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001889 } else {
1890 // do not track any other networks
1891 timeout = 0;
1892 }
1893
Robert Greenwalt7b816022014-04-18 15:25:25 -07001894 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001895 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001896 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001897 } catch (Exception e) {
1898 // You shall not crash!
1899 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001900 }
1901 }
1902 }
1903
1904 /**
1905 * Remove data activity tracking when network disconnects.
1906 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001907 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1908 final String iface = networkAgent.linkProperties.getInterfaceName();
1909 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001910
Robert Greenwalt7b816022014-04-18 15:25:25 -07001911 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1912 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001913 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001914 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08001915 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001916 } catch (Exception e) {
1917 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001918 }
1919 }
1920 }
1921
1922 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08001923 * Update data activity tracking when network state is updated.
1924 */
1925 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
1926 NetworkAgentInfo oldNetwork) {
1927 if (newNetwork != null) {
1928 setupDataActivityTracking(newNetwork);
1929 }
1930 if (oldNetwork != null) {
1931 removeDataActivityTracking(oldNetwork);
1932 }
1933 }
1934 /**
Chalard Jean4d660112018-06-04 16:52:49 +09001935 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09001936 * and set it on it's iface.
1937 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001938 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1939 final String iface = newLp.getInterfaceName();
1940 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001941 if (oldLp == null && mtu == 0) {
1942 // Silently ignore unset MTU value.
1943 return;
1944 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001945 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1946 if (VDBG) log("identical MTU - not setting");
1947 return;
1948 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001949 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001950 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001951 return;
1952 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001953
w1997615afd812014-08-05 15:18:11 -07001954 // Cannot set MTU without interface name
1955 if (TextUtils.isEmpty(iface)) {
1956 loge("Setting MTU size with null iface.");
1957 return;
1958 }
1959
Robert Greenwalt7b816022014-04-18 15:25:25 -07001960 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001961 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08001962 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 } catch (Exception e) {
1964 Slog.e(TAG, "exception in setMtu()" + e);
1965 }
1966 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001967
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001968 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001969 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1970
1971 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001972 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001973 protected MockableSystemProperties getSystemProperties() {
1974 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001975 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001976
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001977 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1978 if (isDefaultNetwork(nai) == false) {
1979 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001980 }
1981
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001982 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1983 String[] values = null;
1984 if (tcpBufferSizes != null) {
1985 values = tcpBufferSizes.split(",");
1986 }
1987
1988 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001989 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001990 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1991 values = tcpBufferSizes.split(",");
1992 }
1993
1994 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1995
1996 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001997 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001998
1999 final String prefix = "/sys/kernel/ipv4/tcp_";
2000 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2001 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2002 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2003 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2004 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2005 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2006 mCurrentTcpBufferSizes = tcpBufferSizes;
2007 } catch (IOException e) {
2008 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002009 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002010
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002011 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002012 Settings.Global.TCP_DEFAULT_INIT_RWND,
2013 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002014 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2015 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002016 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002017 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002018 }
2019
Robert Greenwalt562cc542014-05-15 18:07:26 -07002020 @Override
2021 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002022 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002023 NETWORK_RESTORE_DELAY_PROP_NAME);
2024 if(restoreDefaultNetworkDelayStr != null &&
2025 restoreDefaultNetworkDelayStr.length() != 0) {
2026 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002027 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002028 } catch (NumberFormatException e) {
2029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002031 // if the system property isn't set, use the value for the apn type
2032 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2033
2034 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2035 (mNetConfigs[networkType] != null)) {
2036 ret = mNetConfigs[networkType].restoreTime;
2037 }
2038 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
2040
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002041 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2042 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2043 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002044 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002045 // Start gathering diagnostic information.
2046 netDiags.add(new NetworkDiagnostics(
2047 nai.network,
2048 new LinkProperties(nai.linkProperties), // Must be a copy.
2049 DIAG_TIME_MS));
2050 }
2051
2052 for (NetworkDiagnostics netDiag : netDiags) {
2053 pw.println();
2054 netDiag.waitForMeasurements();
2055 netDiag.dump(pw);
2056 }
2057 }
2058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002060 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002061 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2062 }
2063
2064 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002065 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002066 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002067 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002068
Erik Kline3f8306b2018-05-01 16:51:44 +09002069 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002070 dumpNetworkDiagnostics(pw);
2071 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002072 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002073 mTethering.dump(fd, pw, args);
2074 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002075 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2076 dumpNetworks(pw);
2077 return;
2078 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2079 dumpNetworkRequests(pw);
2080 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002081 }
Erik Kline379747a2015-06-05 17:47:34 +09002082
Lorenzo Colittie3805462015-06-03 11:18:24 +09002083 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002084 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002085 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002086 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002087 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002088 pw.println();
2089
Paul Jensen85cf78e2015-06-25 13:25:07 -04002090 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002091 pw.print("Active default network: ");
2092 if (defaultNai == null) {
2093 pw.println("none");
2094 } else {
2095 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002097 pw.println();
2098
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002099 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002100 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002101 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002102 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002103 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002104
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002105 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002106 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002107 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002108 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002109 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002110
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002111 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002112
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002113 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002114 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002115
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002116 pw.println();
2117 mKeepaliveTracker.dump(pw);
2118
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002119 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002120 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002121
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002122 pw.println();
2123 mMultipathPolicyTracker.dump(pw);
2124
Erik Kline3f8306b2018-05-01 16:51:44 +09002125 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002126 pw.println();
2127 synchronized (mValidationLogs) {
2128 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002129 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002130 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002131 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002132 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002133 pw.decreaseIndent();
2134 }
2135 }
Erik Kline7523eb32015-07-09 18:24:03 +09002136
2137 pw.println();
2138 pw.println("mNetworkRequestInfoLogs (most recent first):");
2139 pw.increaseIndent();
2140 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2141 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002142
2143 pw.println();
2144 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2145 pw.increaseIndent();
2146 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2147 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002148
2149 pw.println();
2150 pw.println("NetTransition WakeLock activity (most recent first):");
2151 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002152 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2153 pw.println("total releases: " + mTotalWakelockReleases);
2154 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2155 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2156 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2157 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2158 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2159 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002160 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002161
2162 pw.println();
2163 pw.println("bandwidth update requests (by uid):");
2164 pw.increaseIndent();
2165 synchronized (mBandwidthRequests) {
2166 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2167 pw.println("[" + mBandwidthRequests.keyAt(i)
2168 + "]: " + mBandwidthRequests.valueAt(i));
2169 }
2170 }
2171 pw.decreaseIndent();
2172
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002173 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
2176
Hugo Benichi14683812018-09-03 08:32:56 +09002177 private void dumpNetworks(IndentingPrintWriter pw) {
2178 for (NetworkAgentInfo nai : networksSortedById()) {
2179 pw.println(nai.toString());
2180 pw.increaseIndent();
2181 pw.println(String.format(
2182 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2183 nai.numForegroundNetworkRequests(),
2184 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2185 nai.numBackgroundNetworkRequests(),
2186 nai.numNetworkRequests()));
2187 pw.increaseIndent();
2188 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2189 pw.println(nai.requestAt(i).toString());
2190 }
2191 pw.decreaseIndent();
2192 pw.println("Lingered:");
2193 pw.increaseIndent();
2194 nai.dumpLingerTimers(pw);
2195 pw.decreaseIndent();
2196 pw.decreaseIndent();
2197 }
2198 }
2199
2200 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2201 for (NetworkRequestInfo nri : requestsSortedById()) {
2202 pw.println(nri.toString());
2203 }
2204 }
2205
Hugo Benichia2a917c2018-09-03 08:19:02 +09002206 /**
2207 * Return an array of all current NetworkAgentInfos sorted by network id.
2208 */
2209 private NetworkAgentInfo[] networksSortedById() {
2210 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2211 networks = mNetworkAgentInfos.values().toArray(networks);
2212 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2213 return networks;
2214 }
2215
2216 /**
2217 * Return an array of all current NetworkRequest sorted by request id.
2218 */
2219 private NetworkRequestInfo[] requestsSortedById() {
2220 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2221 requests = mNetworkRequests.values().toArray(requests);
2222 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2223 return requests;
2224 }
2225
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002226 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002227 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002228 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002229 if (officialNai != null && officialNai.equals(nai)) return true;
2230 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002231 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002232 " - " + nai);
2233 }
2234 return false;
2235 }
2236
Robert Greenwalt42acef32009-08-12 16:08:25 -07002237 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002238 private class NetworkStateTrackerHandler extends Handler {
2239 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002240 super(looper);
2241 }
2242
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002243 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002245 default:
2246 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002247 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 handleAsyncChannelHalfConnect(msg);
2249 break;
2250 }
2251 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2252 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2253 if (nai != null) nai.asyncChannel.disconnect();
2254 break;
2255 }
2256 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2257 handleAsyncChannelDisconnected(msg);
2258 break;
2259 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002260 }
2261 return true;
2262 }
2263
2264 private void maybeHandleNetworkAgentMessage(Message msg) {
2265 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2266 if (nai == null) {
2267 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002268 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002269 }
2270 return;
2271 }
2272
2273 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002274 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002275 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2276 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002277 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2278 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002279 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002280 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002281 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002282 break;
2283 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002284 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002285 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002286 break;
2287 }
2288 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002289 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002290 updateNetworkInfo(nai, info);
2291 break;
2292 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002293 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002294 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002295 break;
2296 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002297 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002298 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2299 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002300 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002301 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002302 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002303 break;
2304 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002305 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002306 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2307 break;
2308 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002309 }
2310 }
2311
2312 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2313 switch (msg.what) {
2314 default:
2315 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002316 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002317 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002318 if (nai == null) break;
2319
2320 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2321 final boolean wasValidated = nai.lastValidated;
2322 final boolean wasDefault = isDefaultNetwork(nai);
2323
Erik Klinea24d4592018-01-11 21:07:29 +09002324 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2325
Erik Klinea24d4592018-01-11 21:07:29 +09002326 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002327 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2328 ? " with redirect to " + redirectUrl
2329 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002330 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2331 }
Erik Klinea24d4592018-01-11 21:07:29 +09002332 if (valid != nai.lastValidated) {
2333 if (wasDefault) {
2334 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2335 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002336 }
Erik Klinea24d4592018-01-11 21:07:29 +09002337 final int oldScore = nai.getCurrentScore();
2338 nai.lastValidated = valid;
2339 nai.everValidated |= valid;
2340 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2341 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2342 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002343 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002344 }
2345 updateInetCondition(nai);
2346 // Let the NetworkAgent know the state of its network
2347 Bundle redirectUrlBundle = new Bundle();
2348 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2349 nai.asyncChannel.sendMessage(
2350 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2351 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2352 0, redirectUrlBundle);
2353 if (wasValidated && !nai.lastValidated) {
2354 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002355 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002356 break;
2357 }
Paul Jensen869868be2014-05-15 10:33:05 -04002358 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002359 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002360 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002361 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002362 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002363 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002364 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002365 nai.lastCaptivePortalDetected = visible;
2366 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002367 if (nai.lastCaptivePortalDetected &&
2368 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2369 if (DBG) log("Avoiding captive portal network: " + nai.name());
2370 nai.asyncChannel.sendMessage(
2371 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2372 teardownUnneededNetwork(nai);
2373 break;
2374 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002375 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002376 }
2377 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002378 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002379 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002380 if (nai == null) {
2381 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2382 break;
2383 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002384 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002385 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002386 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002387 }
Paul Jensen869868be2014-05-15 10:33:05 -04002388 }
Paul Jensen869868be2014-05-15 10:33:05 -04002389 break;
2390 }
Erik Klinea24d4592018-01-11 21:07:29 +09002391 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002392 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002393 if (nai == null) break;
2394
Erik Kline736353a2018-03-21 07:18:33 -07002395 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002396 break;
2397 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002398 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002399 return true;
2400 }
2401
Calvin Onbe96da12016-10-11 15:10:46 -07002402 private int getCaptivePortalMode() {
2403 return Settings.Global.getInt(mContext.getContentResolver(),
2404 Settings.Global.CAPTIVE_PORTAL_MODE,
2405 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2406 }
2407
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002408 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2409 switch (msg.what) {
2410 default:
2411 return false;
2412 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2413 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2414 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2415 handleLingerComplete(nai);
2416 }
2417 break;
2418 }
2419 }
2420 return true;
2421 }
2422
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002423 @Override
2424 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002425 if (!maybeHandleAsyncChannelMessage(msg) &&
2426 !maybeHandleNetworkMonitorMessage(msg) &&
2427 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002428 maybeHandleNetworkAgentMessage(msg);
2429 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002430 }
2431 }
2432
Erik Kline736353a2018-03-21 07:18:33 -07002433 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2434 return NetworkMonitor.isValidationRequired(
2435 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2436 }
2437
Erik Klinec6d00222018-06-26 18:53:43 +09002438 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2439 if (nai == null) return;
2440 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2441 // in order to restart a validation pass from within netd.
2442 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2443 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2444 updateDnses(nai.linkProperties, null, nai.network.netId);
2445 }
2446 }
2447
Erik Klinea24d4592018-01-11 21:07:29 +09002448 private void handlePrivateDnsSettingsChanged() {
2449 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2450
2451 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002452 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002453 if (networkRequiresValidation(nai)) {
2454 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2455 }
Erik Klinea24d4592018-01-11 21:07:29 +09002456 }
2457 }
2458
Erik Kline736353a2018-03-21 07:18:33 -07002459 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2460 // Private DNS only ever applies to networks that might provide
2461 // Internet access and therefore also require validation.
2462 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002463
Erik Kline736353a2018-03-21 07:18:33 -07002464 // Notify the NetworkMonitor thread in case it needs to cancel or
2465 // schedule DNS resolutions. If a DNS resolution is required the
2466 // result will be sent back to us.
2467 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2468
2469 // With Private DNS bypass support, we can proceed to update the
2470 // Private DNS config immediately, even if we're in strict mode
2471 // and have not yet resolved the provider name into a set of IPs.
2472 updatePrivateDns(nai, cfg);
2473 }
2474
2475 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2476 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002477 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002478 }
2479
dalyk7301aa42018-03-05 12:42:22 -05002480 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2481 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2482 if (nai == null) {
2483 return;
2484 }
2485 mDnsManager.updatePrivateDnsValidation(update);
2486 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2487 }
2488
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002489 private void updateLingerState(NetworkAgentInfo nai, long now) {
2490 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2491 // 2. If the network was lingering and there are now requests, unlinger it.
2492 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2493 // one lingered request, start lingering.
2494 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002495 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002496 if (DBG) log("Unlingering " + nai.name());
2497 nai.unlinger();
2498 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002499 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002500 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002501 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002502 nai.linger();
2503 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2504 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2505 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002506 }
2507
Robert Greenwalt7b816022014-04-18 15:25:25 -07002508 private void handleAsyncChannelHalfConnect(Message msg) {
2509 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002510 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002511 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2512 if (VDBG) log("NetworkFactory connected");
2513 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002514 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002515 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002516 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002517 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002518 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002519 }
2520 } else {
2521 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002522 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002523 }
2524 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2525 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2526 if (VDBG) log("NetworkAgent connected");
2527 // A network agent has requested a connection. Establish the connection.
2528 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2529 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2530 } else {
2531 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002532 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002534 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002535 synchronized (mNetworkForNetId) {
2536 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002537 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002538 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002539 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002540 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002541 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002542 }
2543 }
2544 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002545
Chalard Jean392971c2018-05-11 20:19:20 +09002546 // This is a no-op if it's called with a message designating a network that has
2547 // already been destroyed, because its reference will not be found in the relevant
2548 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002549 private void handleAsyncChannelDisconnected(Message msg) {
2550 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2551 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002552 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002553 } else {
2554 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2555 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002556 }
2557 }
2558
Chalard Jean392971c2018-05-11 20:19:20 +09002559 // Destroys a network, remove references to it from the internal state managed by
2560 // ConnectivityService, free its interfaces and clean up.
2561 // Must be called on the Handler thread.
2562 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2563 if (DBG) {
2564 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2565 }
2566 // A network agent has disconnected.
2567 // TODO - if we move the logic to the network agent (have them disconnect
2568 // because they lost all their requests or because their score isn't good)
2569 // then they would disconnect organically, report their new state and then
2570 // disconnect the channel.
2571 if (nai.networkInfo.isConnected()) {
2572 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2573 null, null);
2574 }
2575 final boolean wasDefault = isDefaultNetwork(nai);
2576 if (wasDefault) {
2577 mDefaultInetConditionPublished = 0;
2578 // Log default network disconnection before required book-keeping.
2579 // Let rematchAllNetworksAndRequests() below record a new default network event
2580 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2581 // whose timestamps tell how long it takes to recover a default network.
2582 long now = SystemClock.elapsedRealtime();
2583 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2584 }
2585 notifyIfacesChangedForNetworkStats();
2586 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2587 // by other networks that are already connected. Perhaps that can be done by
2588 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2589 // of rematchAllNetworksAndRequests
2590 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2591 mKeepaliveTracker.handleStopAllKeepalives(nai,
2592 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2593 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2594 // Disable wakeup packet monitoring for each interface.
2595 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2596 }
2597 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2598 mNetworkAgentInfos.remove(nai.messenger);
2599 nai.maybeStopClat();
2600 synchronized (mNetworkForNetId) {
2601 // Remove the NetworkAgent, but don't mark the netId as
2602 // available until we've told netd to delete it below.
2603 mNetworkForNetId.remove(nai.network.netId);
2604 }
2605 // Remove all previously satisfied requests.
2606 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2607 NetworkRequest request = nai.requestAt(i);
2608 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2609 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2610 clearNetworkForRequest(request.requestId);
2611 sendUpdatedScoreToFactories(request, 0);
2612 }
2613 }
2614 nai.clearLingerState();
2615 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002616 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002617 notifyLockdownVpn(nai);
2618 ensureNetworkTransitionWakelock(nai.name());
2619 }
2620 mLegacyTypeTracker.remove(nai, wasDefault);
2621 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2622 updateAllVpnsCapabilities();
2623 }
2624 rematchAllNetworksAndRequests(null, 0);
2625 mLingerMonitor.noteDisconnect(nai);
2626 if (nai.created) {
2627 // Tell netd to clean up the configuration for this network
2628 // (routing rules, DNS, etc).
2629 // This may be slow as it requires a lot of netd shelling out to ip and
2630 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2631 // after we've rematched networks with requests which should make a potential
2632 // fallback network the default or requested a new network from the
2633 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2634 // long time.
2635 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002636 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002637 } catch (Exception e) {
2638 loge("Exception removing network: " + e);
2639 }
2640 mDnsManager.removeNetwork(nai.network);
2641 }
2642 synchronized (mNetworkForNetId) {
2643 mNetIdInUse.delete(nai.network.netId);
2644 }
2645 }
2646
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002647 // If this method proves to be too slow then we can maintain a separate
2648 // pendingIntent => NetworkRequestInfo map.
2649 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2650 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2651 Intent intent = pendingIntent.getIntent();
2652 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2653 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2654 if (existingPendingIntent != null &&
2655 existingPendingIntent.getIntent().filterEquals(intent)) {
2656 return entry.getValue();
2657 }
2658 }
2659 return null;
2660 }
2661
2662 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2663 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2664
2665 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2666 if (existingRequest != null) { // remove the existing request.
2667 if (DBG) log("Replacing " + existingRequest.request + " with "
2668 + nri.request + " because their intents matched.");
2669 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2670 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002671 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002672 }
2673
Erik Klineda4bfa82015-04-30 12:58:40 +09002674 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002675 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002676 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002677 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002678 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002679 if (nri.request.networkCapabilities.hasSignalStrength() &&
2680 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2681 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002682 }
2683 }
2684 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002685 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002686 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002687 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002688 }
2689 }
2690
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002691 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2692 int callingUid) {
2693 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2694 if (nri != null) {
2695 handleReleaseNetworkRequest(nri.request, callingUid);
2696 }
2697 }
2698
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002699 // Determines whether the network is the best (or could become the best, if it validated), for
2700 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2701 // on the value of reason:
2702 //
2703 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2704 // then it should be torn down.
2705 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2706 // then it should be lingered.
2707 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2708 final int numRequests;
2709 switch (reason) {
2710 case TEARDOWN:
2711 numRequests = nai.numRequestNetworkRequests();
2712 break;
2713 case LINGER:
2714 numRequests = nai.numForegroundNetworkRequests();
2715 break;
2716 default:
2717 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2718 return true;
2719 }
2720
2721 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002722 return false;
2723 }
Paul Jensene0988542015-06-25 15:30:08 -04002724 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002725 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2726 // Background requests don't affect lingering.
2727 continue;
2728 }
2729
Paul Jensene0988542015-06-25 15:30:08 -04002730 // If this Network is already the highest scoring Network for a request, or if
2731 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002732 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002733 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002734 // Note that this catches two important cases:
2735 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2736 // is currently satisfying the request. This is desirable when
2737 // cellular ends up validating but WiFi does not.
2738 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002739 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002740 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002741 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002742 nai.getCurrentScoreAsValidated())) {
2743 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002744 }
2745 }
Paul Jensene0988542015-06-25 15:30:08 -04002746 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002747 }
2748
Erik Klineacdd6392016-07-07 16:50:58 +09002749 private NetworkRequestInfo getNriForAppRequest(
2750 NetworkRequest request, int callingUid, String requestedOperation) {
2751 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2752
Robert Greenwalt9258c642014-03-26 16:47:06 -07002753 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002754 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002755 log(String.format("UID %d attempted to %s for unowned request %s",
2756 callingUid, requestedOperation, nri));
2757 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002758 }
Erik Klineacdd6392016-07-07 16:50:58 +09002759 }
2760
2761 return nri;
2762 }
2763
Erik Kline57faba92015-11-25 12:49:38 +09002764 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002765 if (mNetworkRequests.get(nri.request) == null) {
2766 return;
Erik Kline57faba92015-11-25 12:49:38 +09002767 }
Hugo Benichicd952782017-09-20 11:20:14 +09002768 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002769 return;
2770 }
2771 if (VDBG || (DBG && nri.request.isRequest())) {
2772 log("releasing " + nri.request + " (timeout)");
2773 }
2774 handleRemoveNetworkRequest(nri);
2775 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002776 }
2777
Erik Klineacdd6392016-07-07 16:50:58 +09002778 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002779 final NetworkRequestInfo nri =
2780 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2781 if (nri == null) {
2782 return;
Erik Kline57faba92015-11-25 12:49:38 +09002783 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002784 if (VDBG || (DBG && nri.request.isRequest())) {
2785 log("releasing " + nri.request + " (release request)");
2786 }
2787 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002788 }
Erik Klineacdd6392016-07-07 16:50:58 +09002789
Hugo Benichidba33db2017-03-23 22:40:44 +09002790 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002791 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002792 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002793
Erik Klineacdd6392016-07-07 16:50:58 +09002794 synchronized (mUidToNetworkRequestCount) {
2795 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2796 if (requests < 1) {
2797 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2798 nri.mUid);
2799 } else if (requests == 1) {
2800 mUidToNetworkRequestCount.removeAt(
2801 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2802 } else {
2803 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2804 }
2805 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002806
Erik Klineacdd6392016-07-07 16:50:58 +09002807 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2808 if (nri.request.isRequest()) {
2809 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002810 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002811 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002812 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002813 nai.removeRequest(nri.request.requestId);
2814 if (VDBG) {
2815 log(" Removing from current network " + nai.name() +
2816 ", leaving " + nai.numNetworkRequests() + " requests.");
2817 }
2818 // If there are still lingered requests on this network, don't tear it down,
2819 // but resume lingering instead.
2820 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002821 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002822 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2823 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002824 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002825 wasKept = true;
2826 }
Hugo Benichicd952782017-09-20 11:20:14 +09002827 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002828 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2829 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002830 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002831 }
Erik Klineacdd6392016-07-07 16:50:58 +09002832 }
2833
Erik Klineacdd6392016-07-07 16:50:58 +09002834 // Maintain the illusion. When this request arrived, we might have pretended
2835 // that a network connected to serve it, even though the network was already
2836 // connected. Now that this request has gone away, we might have to pretend
2837 // that the network disconnected. LegacyTypeTracker will generate that
2838 // phantom disconnect for this type.
2839 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2840 boolean doRemove = true;
2841 if (wasKept) {
2842 // check if any of the remaining requests for this network are for the
2843 // same legacy type - if so, don't remove the nai
2844 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2845 NetworkRequest otherRequest = nai.requestAt(i);
2846 if (otherRequest.legacyType == nri.request.legacyType &&
2847 otherRequest.isRequest()) {
2848 if (DBG) log(" still have other legacy request - leaving");
2849 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002850 }
2851 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002852 }
2853
Erik Klineacdd6392016-07-07 16:50:58 +09002854 if (doRemove) {
2855 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002856 }
2857 }
Erik Klineacdd6392016-07-07 16:50:58 +09002858
2859 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2860 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2861 nri.request);
2862 }
2863 } else {
2864 // listens don't have a singular affectedNetwork. Check all networks to see
2865 // if this listen request applies and remove it.
2866 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2867 nai.removeRequest(nri.request.requestId);
2868 if (nri.request.networkCapabilities.hasSignalStrength() &&
2869 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2870 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2871 }
2872 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002873 }
2874 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002875
Lorenzo Colitti18660282016-07-04 12:55:44 +09002876 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002877 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2878 enforceConnectivityInternalPermission();
2879 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002880 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002881 }
2882
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002883 @Override
2884 public void setAvoidUnvalidated(Network network) {
2885 enforceConnectivityInternalPermission();
2886 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2887 }
2888
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002889 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2890 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2891 " accept=" + accept + " always=" + always);
2892
2893 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2894 if (nai == null) {
2895 // Nothing to do.
2896 return;
2897 }
2898
2899 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002900 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002901 return;
2902 }
2903
2904 if (!nai.networkMisc.explicitlySelected) {
2905 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2906 }
2907
2908 if (accept != nai.networkMisc.acceptUnvalidated) {
2909 int oldScore = nai.getCurrentScore();
2910 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002911 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002912 sendUpdatedScoreToFactories(nai);
2913 }
2914
2915 if (always) {
2916 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002917 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002918 }
2919
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002920 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002921 // Tell the NetworkAgent to not automatically reconnect to the network.
2922 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09002923 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04002924 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002925 }
2926
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002927 }
2928
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002929 private void handleSetAvoidUnvalidated(Network network) {
2930 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2931 if (nai == null || nai.lastValidated) {
2932 // Nothing to do. The network either disconnected or revalidated.
2933 return;
2934 }
2935 if (!nai.avoidUnvalidated) {
2936 int oldScore = nai.getCurrentScore();
2937 nai.avoidUnvalidated = true;
2938 rematchAllNetworksAndRequests(nai, oldScore);
2939 sendUpdatedScoreToFactories(nai);
2940 }
2941 }
2942
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002943 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002944 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002945 mHandler.sendMessageDelayed(
2946 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2947 PROMPT_UNVALIDATED_DELAY_MS);
2948 }
2949
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002950 @Override
2951 public void startCaptivePortalApp(Network network) {
2952 enforceConnectivityInternalPermission();
2953 mHandler.post(() -> {
2954 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2955 if (nai == null) return;
2956 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2957 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2958 });
2959 }
2960
Hugo Benichic8e9e122016-09-14 23:23:08 +00002961 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002962 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002963 }
2964
Erik Kline065ab6e2016-10-02 18:02:14 +09002965 private void rematchForAvoidBadWifiUpdate() {
2966 rematchAllNetworksAndRequests(null, 0);
2967 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2968 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2969 sendUpdatedScoreToFactories(nai);
2970 }
2971 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002972 }
2973
Erik Kline065ab6e2016-10-02 18:02:14 +09002974 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002975 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002976 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002977 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002978 if (!configRestrict) {
2979 pw.println("Bad Wi-Fi avoidance: unrestricted");
2980 return;
2981 }
2982
2983 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2984 pw.increaseIndent();
2985 pw.println("Config restrict: " + configRestrict);
2986
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002987 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002988 String description;
2989 // Can't use a switch statement because strings are legal case labels, but null is not.
2990 if ("0".equals(value)) {
2991 description = "get stuck";
2992 } else if (value == null) {
2993 description = "prompt";
2994 } else if ("1".equals(value)) {
2995 description = "avoid";
2996 } else {
2997 description = value + " (?)";
2998 }
2999 pw.println("User setting: " + description);
3000 pw.println("Network overrides:");
3001 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003002 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003003 if (nai.avoidUnvalidated) {
3004 pw.println(nai.name());
3005 }
3006 }
3007 pw.decreaseIndent();
3008 pw.decreaseIndent();
3009 }
3010
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003011 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
3012 final String action;
3013 switch (type) {
3014 case NO_INTERNET:
3015 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3016 break;
3017 case LOST_INTERNET:
3018 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3019 break;
3020 default:
3021 Slog.wtf(TAG, "Unknown notification type " + type);
3022 return;
3023 }
3024
3025 Intent intent = new Intent(action);
3026 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3027 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3028 intent.setClassName("com.android.settings",
3029 "com.android.settings.wifi.WifiNoInternetDialog");
3030
3031 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3032 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3033 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3034 }
3035
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003036 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003037 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003038 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3039
3040 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3041 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003042 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003043 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003044 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3045 return;
3046 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003047 showValidationNotification(nai, NotificationType.NO_INTERNET);
3048 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003049
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003050 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3051 NetworkCapabilities nc = nai.networkCapabilities;
3052 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003053
Erik Kline065ab6e2016-10-02 18:02:14 +09003054 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003055 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003056 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3057 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003058 }
3059
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003060 @Override
3061 public int getMultipathPreference(Network network) {
3062 enforceAccessPermission();
3063
3064 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003065 if (nai != null && nai.networkCapabilities
3066 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003067 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3068 }
3069
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003070 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3071 if (networkPreference != null) {
3072 return networkPreference;
3073 }
3074
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003075 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3076 }
3077
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003078 private class InternalHandler extends Handler {
3079 public InternalHandler(Looper looper) {
3080 super(looper);
3081 }
3082
3083 @Override
3084 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003085 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003086 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003087 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003088 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003089 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003090 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003091 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003092 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003093 break;
3094 }
Jason Monkdecd2952013-10-10 14:02:51 -04003095 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003096 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003097 break;
3098 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003099 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003100 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3101 break;
3102 }
3103 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3104 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003105 break;
3106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003107 case EVENT_REGISTER_NETWORK_AGENT: {
3108 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3109 break;
3110 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003111 case EVENT_REGISTER_NETWORK_REQUEST:
3112 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003113 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003114 break;
3115 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003116 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3117 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003118 handleRegisterNetworkRequestWithIntent(msg);
3119 break;
3120 }
Erik Kline57faba92015-11-25 12:49:38 +09003121 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3122 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3123 handleTimedOutNetworkRequest(nri);
3124 break;
3125 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003126 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3127 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3128 break;
3129 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003130 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003131 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003132 break;
3133 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003134 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003135 Network network = (Network) msg.obj;
3136 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003137 break;
3138 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003139 case EVENT_SET_AVOID_UNVALIDATED: {
3140 handleSetAvoidUnvalidated((Network) msg.obj);
3141 break;
3142 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003143 case EVENT_PROMPT_UNVALIDATED: {
3144 handlePromptUnvalidated((Network) msg.obj);
3145 break;
3146 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003147 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3148 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003149 break;
3150 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003151 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3152 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3153 mKeepaliveTracker.handleStartKeepalive(msg);
3154 break;
3155 }
3156 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3157 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3158 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3159 int slot = msg.arg1;
3160 int reason = msg.arg2;
3161 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3162 break;
3163 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003164 case EVENT_SYSTEM_READY: {
3165 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3166 nai.networkMonitor.systemReady = true;
3167 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003168 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003169 break;
3170 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003171 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003172 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003173 break;
3174 }
Erik Klinea24d4592018-01-11 21:07:29 +09003175 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3176 handlePrivateDnsSettingsChanged();
3177 break;
dalyk7301aa42018-03-05 12:42:22 -05003178 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3179 handlePrivateDnsValidationUpdate(
3180 (PrivateDnsValidationUpdate) msg.obj);
3181 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 }
3183 }
3184 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003185
3186 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003187 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003188 public int tether(String iface, String callerPkg) {
3189 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003190 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003191 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003192 } else {
3193 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3194 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003195 }
3196
3197 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003198 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003199 public int untether(String iface, String callerPkg) {
3200 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003201
3202 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003203 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003204 } else {
3205 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3206 }
3207 }
3208
3209 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003210 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003211 public int getLastTetherError(String iface) {
3212 enforceTetherAccessPermission();
3213
3214 if (isTetheringSupported()) {
3215 return mTethering.getLastTetherError(iface);
3216 } else {
3217 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3218 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003219 }
3220
3221 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003222 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003223 public String[] getTetherableUsbRegexs() {
3224 enforceTetherAccessPermission();
3225 if (isTetheringSupported()) {
3226 return mTethering.getTetherableUsbRegexs();
3227 } else {
3228 return new String[0];
3229 }
3230 }
3231
Lorenzo Colitti18660282016-07-04 12:55:44 +09003232 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003233 public String[] getTetherableWifiRegexs() {
3234 enforceTetherAccessPermission();
3235 if (isTetheringSupported()) {
3236 return mTethering.getTetherableWifiRegexs();
3237 } else {
3238 return new String[0];
3239 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003240 }
3241
Lorenzo Colitti18660282016-07-04 12:55:44 +09003242 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003243 public String[] getTetherableBluetoothRegexs() {
3244 enforceTetherAccessPermission();
3245 if (isTetheringSupported()) {
3246 return mTethering.getTetherableBluetoothRegexs();
3247 } else {
3248 return new String[0];
3249 }
3250 }
3251
Lorenzo Colitti18660282016-07-04 12:55:44 +09003252 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003253 public int setUsbTethering(boolean enable, String callerPkg) {
3254 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003255 if (isTetheringSupported()) {
3256 return mTethering.setUsbTethering(enable);
3257 } else {
3258 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3259 }
3260 }
3261
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003262 // TODO - move iface listing, queries, etc to new module
3263 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003264 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003265 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003266 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003267 return mTethering.getTetherableIfaces();
3268 }
3269
Lorenzo Colitti18660282016-07-04 12:55:44 +09003270 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003271 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003272 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003273 return mTethering.getTetheredIfaces();
3274 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003275
Lorenzo Colitti18660282016-07-04 12:55:44 +09003276 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003277 public String[] getTetheringErroredIfaces() {
3278 enforceTetherAccessPermission();
3279 return mTethering.getErroredIfaces();
3280 }
3281
Lorenzo Colitti18660282016-07-04 12:55:44 +09003282 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003283 public String[] getTetheredDhcpRanges() {
3284 enforceConnectivityInternalPermission();
3285 return mTethering.getTetheredDhcpRanges();
3286 }
3287
Udam Saini0e94c362017-06-07 12:06:28 -07003288 @Override
3289 public boolean isTetheringSupported(String callerPkg) {
3290 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3291 return isTetheringSupported();
3292 }
3293
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003294 // if ro.tether.denied = true we default to no tethering
3295 // gservices could set the secure setting to 1 though to enable it on a build where it
3296 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003297 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003298 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3299 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3300 Settings.Global.TETHER_SUPPORTED, defaultVal));
3301 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003302 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003303
3304 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3305 boolean adminUser = false;
3306 final long token = Binder.clearCallingIdentity();
3307 try {
3308 adminUser = mUserManager.isAdminUser();
3309 } finally {
3310 Binder.restoreCallingIdentity(token);
3311 }
3312
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003313 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003314 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003315
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003316 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003317 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3318 String callerPkg) {
3319 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003320 if (!isTetheringSupported()) {
3321 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3322 return;
3323 }
3324 mTethering.startTethering(type, receiver, showProvisioningUi);
3325 }
3326
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003327 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003328 public void stopTethering(int type, String callerPkg) {
3329 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003330 mTethering.stopTethering(type);
3331 }
3332
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003333 // Called when we lose the default network and have no replacement yet.
3334 // This will automatically be cleared after X seconds or a new default network
3335 // becomes CONNECTED, whichever happens first. The timer is started by the
3336 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003337 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003338 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003339 if (mNetTransitionWakeLock.isHeld()) {
3340 return;
3341 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003342 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003343 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3344 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003345 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003346 mWakelockLogs.log("ACQUIRE for " + forWhom);
3347 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3348 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003349 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003350
Hugo Benichi4c31b342017-03-30 23:18:10 +09003351 // Called when we gain a new default network to release the network transition wakelock in a
3352 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3353 // message is cancelled.
3354 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003355 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003356 if (!mNetTransitionWakeLock.isHeld()) {
3357 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003358 }
3359 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003360 // Cancel self timeout on wakelock hold.
3361 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3362 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3363 mHandler.sendMessageDelayed(msg, 1000);
3364 }
3365
3366 // Called when either message of ensureNetworkTransitionWakelock or
3367 // scheduleReleaseNetworkTransitionWakelock is processed.
3368 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3369 String event = eventName(eventId);
3370 synchronized (this) {
3371 if (!mNetTransitionWakeLock.isHeld()) {
3372 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3373 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3374 return;
3375 }
3376 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003377 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3378 mTotalWakelockDurationMs += lockDuration;
3379 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3380 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003381 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003382 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003383 }
3384
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003385 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003386 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003387 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003388 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003389 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003390 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003391 }
3392
Lorenzo Colitti18660282016-07-04 12:55:44 +09003393 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003394 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003395 enforceAccessPermission();
3396 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003397 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003398 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003399 mHandler.sendMessage(
3400 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3401 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003402
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003403 private void handleReportNetworkConnectivity(
3404 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003405 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003406 if (network == null) {
3407 nai = getDefaultNetwork();
3408 } else {
3409 nai = getNetworkAgentInfoForNetwork(network);
3410 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003411 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3412 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3413 return;
3414 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003415 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003416 if (hasConnectivity == nai.lastValidated) {
3417 return;
3418 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003419 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003420 int netid = nai.network.netId;
3421 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003422 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003423 // Validating a network that has not yet connected could result in a call to
3424 // rematchNetworkAndRequests() which is not meant to work on such networks.
3425 if (!nai.everConnected) {
3426 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003427 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003428 LinkProperties lp = getLinkProperties(nai);
3429 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3430 return;
3431 }
Erik Kline736353a2018-03-21 07:18:33 -07003432 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003433 }
3434
Lorenzo Colitti18660282016-07-04 12:55:44 +09003435 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003436 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003437 if (network == null) return mProxyTracker.getDefaultProxy();
3438 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003439 if (globalProxy != null) return globalProxy;
3440 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3441 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3442 // caller may not have.
3443 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3444 if (nai == null) return null;
3445 synchronized (nai) {
3446 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3447 if (proxyInfo == null) return null;
3448 return new ProxyInfo(proxyInfo);
3449 }
3450 }
3451
Chalard Jean3c443fc2018-06-07 18:37:59 +09003452 @Override
3453 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003454 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003455 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 }
3457
Chalard Jean5afbc832018-06-07 18:02:37 +09003458 @Override
3459 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003460 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003461 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003462 }
3463
Jason Monk207900c2014-04-25 15:00:09 -04003464 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003465 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003466 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003467 proxy = null;
3468 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003469 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003470 }
3471
Paul Jensene0bef712014-12-10 15:12:18 -05003472 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3473 // This method gets called when any network changes proxy, but the broadcast only ever contains
3474 // the default proxy (even if it hasn't changed).
3475 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3476 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003477 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003478 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3479 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3480
Chalard Jean4949dd72018-06-07 17:41:29 +09003481 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003482 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003483 }
3484 }
3485
Robert Greenwalt434203a2010-10-11 16:00:27 -07003486 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003487 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003488 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003489 if (!TextUtils.isEmpty(proxy)) {
3490 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003491 if (data.length == 0) {
3492 return;
3493 }
3494
Chalard Jean4133a122018-06-04 13:33:12 +09003495 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 int proxyPort = 8080;
3497 if (data.length > 1) {
3498 try {
3499 proxyPort = Integer.parseInt(data[1]);
3500 } catch (NumberFormatException e) {
3501 return;
3502 }
3503 }
Chalard Jean4133a122018-06-04 13:33:12 +09003504 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003505 setGlobalProxy(p);
3506 }
3507 }
3508
Robert Greenwalt434203a2010-10-11 16:00:27 -07003509 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003510 final private HashMap<Uri, Integer> mUriEventMap;
3511 final private Context mContext;
3512 final private Handler mHandler;
3513
3514 SettingsObserver(Context context, Handler handler) {
3515 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003516 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003517 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003518 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003519 }
3520
Erik Klineda4bfa82015-04-30 12:58:40 +09003521 void observe(Uri uri, int what) {
3522 mUriEventMap.put(uri, what);
3523 final ContentResolver resolver = mContext.getContentResolver();
3524 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003525 }
3526
3527 @Override
3528 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003529 Slog.wtf(TAG, "Should never be reached.");
3530 }
3531
3532 @Override
3533 public void onChange(boolean selfChange, Uri uri) {
3534 final Integer what = mUriEventMap.get(uri);
3535 if (what != null) {
3536 mHandler.obtainMessage(what.intValue()).sendToTarget();
3537 } else {
3538 loge("No matching event to send for URI=" + uri);
3539 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003540 }
3541 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003542
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003543 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003544 Slog.d(TAG, s);
3545 }
3546
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003547 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003548 Slog.e(TAG, s);
3549 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003550
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003551 private static void loge(String s, Throwable t) {
3552 Slog.e(TAG, s, t);
3553 }
3554
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003555 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003556 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003557 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3558 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3559 *
3560 * @param oldPackage Package name of the application which currently controls VPN, which will
3561 * be replaced. If there is no such application, this should should either be
3562 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3563 * @param newPackage Package name of the application which should gain control of VPN, or
3564 * {@code null} to disable.
3565 * @param userId User for whom to prepare the new VPN.
3566 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003567 * @hide
3568 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003569 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003570 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3571 int userId) {
3572 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003573
Hugo Benichi20035e02017-04-26 14:53:28 +09003574 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003575 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003576 Vpn vpn = mVpns.get(userId);
3577 if (vpn != null) {
3578 return vpn.prepare(oldPackage, newPackage);
3579 } else {
3580 return false;
3581 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003582 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003583 }
3584
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003585 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003586 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3587 * This method is used by system-privileged apps.
3588 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3589 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3590 *
3591 * @param packageName The package for which authorization state should change.
3592 * @param userId User for whom {@code packageName} is installed.
3593 * @param authorized {@code true} if this app should be able to start a VPN connection without
3594 * explicit user approval, {@code false} if not.
3595 *
Jeff Davidson05542602014-08-11 14:07:27 -07003596 * @hide
3597 */
3598 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003599 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3600 enforceCrossUserPermission(userId);
3601
Hugo Benichi20035e02017-04-26 14:53:28 +09003602 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003603 Vpn vpn = mVpns.get(userId);
3604 if (vpn != null) {
3605 vpn.setPackageAuthorization(packageName, authorized);
3606 }
Jeff Davidson05542602014-08-11 14:07:27 -07003607 }
3608 }
3609
3610 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003611 * Configure a TUN interface and return its file descriptor. Parameters
3612 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003613 * and not available in ConnectivityManager. Permissions are checked in
3614 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003615 * @hide
3616 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003617 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003618 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003620 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003621 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003622 return mVpns.get(user).establish(config);
3623 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003624 }
3625
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003626 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003627 * Start legacy VPN, controlling native daemons as needed. Creates a
3628 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003629 */
3630 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003631 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003632 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003633 final LinkProperties egress = getActiveLinkProperties();
3634 if (egress == null) {
3635 throw new IllegalStateException("Missing active network connection");
3636 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003637 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003638 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003639 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3640 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003641 }
3642
3643 /**
3644 * Return the information of the ongoing legacy VPN. This method is used
3645 * by VpnSettings and not available in ConnectivityManager. Permissions
3646 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003647 */
3648 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003649 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3650 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003651
Hugo Benichi20035e02017-04-26 14:53:28 +09003652 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003653 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003654 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003655 }
3656
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003657 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003658 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3659 * and not available in ConnectivityManager.
3660 */
3661 @Override
3662 public VpnInfo[] getAllVpnInfo() {
3663 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003664 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003665 if (mLockdownEnabled) {
3666 return new VpnInfo[0];
3667 }
3668
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003669 List<VpnInfo> infoList = new ArrayList<>();
3670 for (int i = 0; i < mVpns.size(); i++) {
3671 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3672 if (info != null) {
3673 infoList.add(info);
3674 }
3675 }
3676 return infoList.toArray(new VpnInfo[infoList.size()]);
3677 }
3678 }
3679
3680 /**
3681 * @return VPN information for accounting, or null if we can't retrieve all required
3682 * information, e.g primary underlying iface.
3683 */
3684 @Nullable
3685 private VpnInfo createVpnInfo(Vpn vpn) {
3686 VpnInfo info = vpn.getVpnInfo();
3687 if (info == null) {
3688 return null;
3689 }
3690 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3691 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3692 // the underlyingNetworks list.
3693 if (underlyingNetworks == null) {
3694 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3695 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3696 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3697 }
3698 } else if (underlyingNetworks.length > 0) {
3699 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3700 if (linkProperties != null) {
3701 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3702 }
3703 }
3704 return info.primaryUnderlyingIface == null ? null : info;
3705 }
3706
3707 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003708 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3709 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003710 * Permissions are checked in Vpn class.
3711 * @hide
3712 */
3713 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003714 public VpnConfig getVpnConfig(int userId) {
3715 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003716 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003717 Vpn vpn = mVpns.get(userId);
3718 if (vpn != null) {
3719 return vpn.getVpnConfig();
3720 } else {
3721 return null;
3722 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003723 }
3724 }
3725
Chalard Jean6b65ec72018-05-18 22:02:56 +09003726 /**
3727 * Ask all VPN objects to recompute and update their capabilities.
3728 *
3729 * When underlying networks change, VPNs may have to update capabilities to reflect things
3730 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3731 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3732 * handler thread through their agent, this is asynchronous. When the capabilities objects
3733 * are computed they will be up-to-date as they are computed synchronously from here and
3734 * this is running on the ConnectivityService thread.
3735 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3736 */
3737 private void updateAllVpnsCapabilities() {
3738 synchronized (mVpns) {
3739 for (int i = 0; i < mVpns.size(); i++) {
3740 final Vpn vpn = mVpns.valueAt(i);
3741 vpn.updateCapabilities();
3742 }
3743 }
3744 }
3745
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003746 @Override
3747 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003748 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3749 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3750 return false;
3751 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003752
Hugo Benichi69744342017-11-27 10:57:16 +09003753 synchronized (mVpns) {
3754 // Tear down existing lockdown if profile was removed
3755 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3756 if (mLockdownEnabled) {
3757 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3758 if (profileTag == null) {
3759 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3760 return false;
3761 }
3762 String profileName = new String(profileTag);
3763 final VpnProfile profile = VpnProfile.decode(
3764 profileName, mKeyStore.get(Credentials.VPN + profileName));
3765 if (profile == null) {
3766 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3767 setLockdownTracker(null);
3768 return true;
3769 }
3770 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003771 Vpn vpn = mVpns.get(user);
3772 if (vpn == null) {
3773 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3774 return false;
3775 }
Luke Huang4e25ec62018-09-27 16:58:23 +08003776 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003777 } else {
3778 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003779 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003780 }
3781
3782 return true;
3783 }
3784
3785 /**
3786 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3787 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3788 */
Hugo Benichi69744342017-11-27 10:57:16 +09003789 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003790 private void setLockdownTracker(LockdownVpnTracker tracker) {
3791 // Shutdown any existing tracker
3792 final LockdownVpnTracker existing = mLockdownTracker;
3793 mLockdownTracker = null;
3794 if (existing != null) {
3795 existing.shutdown();
3796 }
3797
Robin Leec3736bc2017-03-10 16:19:54 +00003798 if (tracker != null) {
3799 mLockdownTracker = tracker;
3800 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003801 }
3802 }
3803
Hugo Benichi69744342017-11-27 10:57:16 +09003804 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003805 private void throwIfLockdownEnabled() {
3806 if (mLockdownEnabled) {
3807 throw new IllegalStateException("Unavailable in lockdown mode");
3808 }
3809 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003810
Robin Lee244ce8e2016-01-05 18:03:46 +00003811 /**
Robin Lee17e61832016-05-09 13:46:28 +01003812 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3813 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003814 *
Robin Lee17e61832016-05-09 13:46:28 +01003815 * @return {@code true} if the service was started, the service was already connected, or there
3816 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003817 */
Robin Lee17e61832016-05-09 13:46:28 +01003818 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003819 synchronized (mVpns) {
3820 Vpn vpn = mVpns.get(userId);
3821 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003822 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003823 // exists already.
3824 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3825 return false;
3826 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003827
Robin Lee812800c2016-05-13 15:38:08 +01003828 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003829 }
3830 }
3831
3832 @Override
Charles He36738632017-05-15 17:07:18 +01003833 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3834 enforceSettingsPermission();
3835 enforceCrossUserPermission(userId);
3836
3837 synchronized (mVpns) {
3838 Vpn vpn = mVpns.get(userId);
3839 if (vpn == null) {
3840 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3841 return false;
3842 }
3843 return vpn.isAlwaysOnPackageSupported(packageName);
3844 }
3845 }
3846
3847 @Override
Robin Leedc679712016-05-03 13:23:03 +01003848 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003849 enforceConnectivityInternalPermission();
3850 enforceCrossUserPermission(userId);
3851
Robin Lee244ce8e2016-01-05 18:03:46 +00003852 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003853 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3854 if (LockdownVpnTracker.isEnabled()) {
3855 return false;
3856 }
3857
Robin Lee244ce8e2016-01-05 18:03:46 +00003858 Vpn vpn = mVpns.get(userId);
3859 if (vpn == null) {
3860 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3861 return false;
3862 }
Robin Lee17e61832016-05-09 13:46:28 +01003863 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003864 return false;
3865 }
Robin Lee17e61832016-05-09 13:46:28 +01003866 if (!startAlwaysOnVpn(userId)) {
3867 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003868 return false;
3869 }
3870 }
3871 return true;
3872 }
3873
3874 @Override
3875 public String getAlwaysOnVpnPackage(int userId) {
3876 enforceConnectivityInternalPermission();
3877 enforceCrossUserPermission(userId);
3878
3879 synchronized (mVpns) {
3880 Vpn vpn = mVpns.get(userId);
3881 if (vpn == null) {
3882 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3883 return null;
3884 }
3885 return vpn.getAlwaysOnPackage();
3886 }
3887 }
3888
Wink Savilleab9321d2013-06-29 21:10:57 -07003889 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003890 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003891 // TODO: Remove? Any reason to trigger a provisioning check?
3892 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003893 }
3894
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003895 /** Location to an updatable file listing carrier provisioning urls.
3896 * An example:
3897 *
3898 * <?xml version="1.0" encoding="utf-8"?>
3899 * <provisioningUrls>
3900 * <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 -07003901 * </provisioningUrls>
3902 */
3903 private static final String PROVISIONING_URL_PATH =
3904 "/data/misc/radio/provisioning_urls.xml";
3905 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003906
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003907 /** XML tag for root element. */
3908 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3909 /** XML tag for individual url */
3910 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003911 /** XML attribute for mcc */
3912 private static final String ATTR_MCC = "mcc";
3913 /** XML attribute for mnc */
3914 private static final String ATTR_MNC = "mnc";
3915
Paul Jensen434dde82015-06-11 09:43:30 -04003916 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003917 FileReader fileReader = null;
3918 XmlPullParser parser = null;
3919 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003920
3921 try {
3922 fileReader = new FileReader(mProvisioningUrlFile);
3923 parser = Xml.newPullParser();
3924 parser.setInput(fileReader);
3925 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3926
3927 while (true) {
3928 XmlUtils.nextElement(parser);
3929
3930 String element = parser.getName();
3931 if (element == null) break;
3932
Paul Jensen434dde82015-06-11 09:43:30 -04003933 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003934 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3935 try {
3936 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3937 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3938 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3939 parser.next();
3940 if (parser.getEventType() == XmlPullParser.TEXT) {
3941 return parser.getText();
3942 }
3943 }
3944 }
3945 } catch (NumberFormatException e) {
3946 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3947 }
3948 }
3949 }
3950 return null;
3951 } catch (FileNotFoundException e) {
3952 loge("Carrier Provisioning Urls file not found");
3953 } catch (XmlPullParserException e) {
3954 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3955 } catch (IOException e) {
3956 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3957 } finally {
3958 if (fileReader != null) {
3959 try {
3960 fileReader.close();
3961 } catch (IOException e) {}
3962 }
3963 }
3964 return null;
3965 }
3966
Wink Saville42d4f082013-07-20 20:31:59 -07003967 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003968 public String getMobileProvisioningUrl() {
3969 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003970 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003971 if (TextUtils.isEmpty(url)) {
3972 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003973 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003974 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003975 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003976 }
Wink Saville8cf35602013-07-10 23:00:07 -07003977 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003978 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003979 String phoneNumber = mTelephonyManager.getLine1Number();
3980 if (TextUtils.isEmpty(phoneNumber)) {
3981 phoneNumber = "0000000000";
3982 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003983 url = String.format(url,
3984 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3985 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09003986 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003987 }
3988
Wink Savilleab9321d2013-06-29 21:10:57 -07003989 return url;
3990 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003991
Wink Saville948282b2013-08-29 08:55:16 -07003992 @Override
3993 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003994 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003995 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003996 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3997 return;
3998 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003999 final long ident = Binder.clearCallingIdentity();
4000 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004001 // Concatenate the range of types onto the range of NetIDs.
4002 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4003 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004004 } finally {
4005 Binder.restoreCallingIdentity(ident);
4006 }
Wink Saville948282b2013-08-29 08:55:16 -07004007 }
Wink Saville7788c612013-08-29 14:57:08 -07004008
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004009 @Override
4010 public void setAirplaneMode(boolean enable) {
4011 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004012 final long ident = Binder.clearCallingIdentity();
4013 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004014 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004015 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004016 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4017 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004018 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004019 } finally {
4020 Binder.restoreCallingIdentity(ident);
4021 }
4022 }
4023
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004024 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004025 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004026 Vpn userVpn = mVpns.get(userId);
4027 if (userVpn != null) {
4028 loge("Starting user already has a VPN");
4029 return;
4030 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004031 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004032 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004033 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4034 updateLockdownVpn();
4035 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004036 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004037 }
4038
4039 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004040 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004041 Vpn userVpn = mVpns.get(userId);
4042 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004043 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004044 return;
4045 }
Robin Lee17e61832016-05-09 13:46:28 +01004046 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004047 mVpns.delete(userId);
4048 }
4049 }
4050
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004051 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004052 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004053 final int vpnsSize = mVpns.size();
4054 for (int i = 0; i < vpnsSize; i++) {
4055 Vpn vpn = mVpns.valueAt(i);
4056 vpn.onUserAdded(userId);
4057 }
4058 }
4059 }
4060
4061 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004062 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004063 final int vpnsSize = mVpns.size();
4064 for (int i = 0; i < vpnsSize; i++) {
4065 Vpn vpn = mVpns.valueAt(i);
4066 vpn.onUserRemoved(userId);
4067 }
4068 }
4069 }
4070
Robin Lee89e7a692016-02-29 14:38:17 +00004071 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004072 synchronized (mVpns) {
4073 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4074 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4075 updateLockdownVpn();
4076 } else {
4077 startAlwaysOnVpn(userId);
4078 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004079 }
4080 }
4081
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004082 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4083 @Override
4084 public void onReceive(Context context, Intent intent) {
4085 final String action = intent.getAction();
4086 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4087 if (userId == UserHandle.USER_NULL) return;
4088
Robin Lee323f29d2016-05-04 16:38:06 +01004089 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004090 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004091 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004092 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004093 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4094 onUserAdded(userId);
4095 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4096 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004097 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4098 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004099 }
4100 }
4101 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004102
Robin Lee95204e02017-01-27 11:59:22 +00004103 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4104 @Override
4105 public void onReceive(Context context, Intent intent) {
4106 // Try creating lockdown tracker, since user present usually means
4107 // unlocked keystore.
4108 updateLockdownVpn();
4109 mContext.unregisterReceiver(this);
4110 }
4111 };
4112
Chalard Jean4133a122018-06-04 13:33:12 +09004113 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4114 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004115
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004116 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4117 // Map from UID to number of NetworkRequests that UID has filed.
4118 @GuardedBy("mUidToNetworkRequestCount")
4119 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4120
Robert Greenwalta67be032014-05-16 15:49:14 -07004121 private static class NetworkFactoryInfo {
4122 public final String name;
4123 public final Messenger messenger;
4124 public final AsyncChannel asyncChannel;
4125
4126 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4127 this.name = name;
4128 this.messenger = messenger;
4129 this.asyncChannel = asyncChannel;
4130 }
4131 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004132
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004133 private void ensureNetworkRequestHasType(NetworkRequest request) {
4134 if (request.type == NetworkRequest.Type.NONE) {
4135 throw new IllegalArgumentException(
4136 "All NetworkRequests in ConnectivityService must have a type");
4137 }
4138 }
4139
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004140 /**
4141 * Tracks info about the requester.
4142 * Also used to notice when the calling process dies so we can self-expire
4143 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004145 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004146 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004147 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004149 final int mPid;
4150 final int mUid;
4151 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004153 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004155 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004156 mPendingIntent = pi;
4157 messenger = null;
4158 mBinder = null;
4159 mPid = getCallingPid();
4160 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004161 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004162 }
4163
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004164 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 super();
4166 messenger = m;
4167 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004168 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 mBinder = binder;
4170 mPid = getCallingPid();
4171 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004172 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004173 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004174
4175 try {
4176 mBinder.linkToDeath(this, 0);
4177 } catch (RemoteException e) {
4178 binderDied();
4179 }
4180 }
4181
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004182 private void enforceRequestCountLimit() {
4183 synchronized (mUidToNetworkRequestCount) {
4184 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4185 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004186 throw new ServiceSpecificException(
4187 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004188 }
4189 mUidToNetworkRequestCount.put(mUid, networkRequests);
4190 }
4191 }
4192
Robert Greenwalt9258c642014-03-26 16:47:06 -07004193 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004194 if (mBinder != null) {
4195 mBinder.unlinkToDeath(this, 0);
4196 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 }
4198
4199 public void binderDied() {
4200 log("ConnectivityService NetworkRequestInfo binderDied(" +
4201 request + ", " + mBinder + ")");
4202 releaseNetworkRequest(request);
4203 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004204
4205 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004206 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004207 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004208 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004209 }
4210
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004211 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4212 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4213 if (badCapability != null) {
4214 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004215 }
4216 }
4217
Chalard Jeanb03a6222018-04-11 21:09:10 +09004218 // This checks that the passed capabilities either do not request a specific SSID, or the
4219 // calling app has permission to do so.
4220 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4221 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004222 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004223 throw new SecurityException("Insufficient permissions to request a specific SSID");
4224 }
4225 }
4226
Erik Kline9d598e12015-07-13 16:37:51 +09004227 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004228 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004229 synchronized (nai) {
4230 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4231 if (nri.request.networkCapabilities.hasSignalStrength() &&
4232 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4233 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4234 }
4235 }
4236 }
Chalard Jean4133a122018-06-04 13:33:12 +09004237 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004238 }
4239
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004240 private void updateSignalStrengthThresholds(
4241 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4242 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004243 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004244 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4245
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004246 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004247 String detail;
4248 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4249 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4250 } else {
4251 detail = reason;
4252 }
4253 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4254 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4255 }
4256
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004257 nai.asyncChannel.sendMessage(
4258 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004259 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004260 }
4261
Etan Cohen859748f2017-04-03 17:42:34 -07004262 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4263 if (nc == null) {
4264 return;
4265 }
4266 NetworkSpecifier ns = nc.getNetworkSpecifier();
4267 if (ns == null) {
4268 return;
4269 }
4270 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4271 ns.assertValidFromUid(Binder.getCallingUid());
4272 }
4273
Robert Greenwalt9258c642014-03-26 16:47:06 -07004274 @Override
4275 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004276 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004277 final NetworkRequest.Type type = (networkCapabilities == null)
4278 ? NetworkRequest.Type.TRACK_DEFAULT
4279 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004280 // If the requested networkCapabilities is null, take them instead from
4281 // the default network request. This allows callers to keep track of
4282 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004283 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004284 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004285 enforceAccessPermission();
4286 } else {
4287 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4288 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004289 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4290 // of the app when the request is filed, but we never change the request if the app
4291 // changes network state. http://b/29964605
4292 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004293 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004294 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004295 ensureSufficientPermissionsForRequest(networkCapabilities,
4296 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004297 // Set the UID range for this request to the single UID of the requester, or to an empty
4298 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004299 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4300 // are no visible methods to set the UIDs, an app could use reflection to try and get
4301 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004302 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004303
Etan Cohenba07c8c2017-02-05 10:42:27 -08004304 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004305 throw new IllegalArgumentException("Bad timeout specified");
4306 }
Etan Cohen859748f2017-04-03 17:42:34 -07004307 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004308
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004309 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004310 nextNetworkRequestId(), type);
4311 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004312 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313
4314 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004315 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004316 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004317 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318 }
4319 return networkRequest;
4320 }
4321
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004322 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004323 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004324 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004325 } else {
4326 enforceChangePermission();
4327 }
4328 }
4329
fenglub15e72b2015-03-20 11:29:56 -07004330 @Override
fengludb571472015-04-21 17:12:05 -07004331 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004332 enforceAccessPermission();
4333 NetworkAgentInfo nai = null;
4334 if (network == null) {
4335 return false;
4336 }
4337 synchronized (mNetworkForNetId) {
4338 nai = mNetworkForNetId.get(network.netId);
4339 }
4340 if (nai != null) {
4341 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004342 synchronized (mBandwidthRequests) {
4343 final int uid = Binder.getCallingUid();
4344 Integer uidReqs = mBandwidthRequests.get(uid);
4345 if (uidReqs == null) {
4346 uidReqs = new Integer(0);
4347 }
4348 mBandwidthRequests.put(uid, ++uidReqs);
4349 }
fenglub15e72b2015-03-20 11:29:56 -07004350 return true;
4351 }
4352 return false;
4353 }
4354
Felipe Lemeee27cab2016-06-20 16:36:29 -07004355 private boolean isSystem(int uid) {
4356 return uid < Process.FIRST_APPLICATION_UID;
4357 }
fenglub15e72b2015-03-20 11:29:56 -07004358
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004359 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004360 final int uid = Binder.getCallingUid();
4361 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004362 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004363 return;
4364 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004365 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4366 // Policy already enforced.
4367 return;
4368 }
4369 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4370 // If UID is restricted, don't allow them to bring up metered APNs.
4371 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004372 }
4373 }
4374
Robert Greenwalt9258c642014-03-26 16:47:06 -07004375 @Override
4376 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4377 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004378 checkNotNull(operation, "PendingIntent cannot be null.");
4379 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4380 enforceNetworkRequestPermissions(networkCapabilities);
4381 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004382 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004383 ensureSufficientPermissionsForRequest(networkCapabilities,
4384 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004385 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004386 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004387
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004388 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004389 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4390 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004391 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4393 nri));
4394 return networkRequest;
4395 }
4396
Jeremy Joslin79294842014-12-03 17:15:28 -08004397 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4398 mHandler.sendMessageDelayed(
4399 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4400 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4401 }
4402
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004403 @Override
4404 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004405 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4407 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004408 }
4409
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004410 // In order to implement the compatibility measure for pre-M apps that call
4411 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4412 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4413 // This ensures it has permission to do so.
4414 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4415 if (nc == null) {
4416 return false;
4417 }
4418 int[] transportTypes = nc.getTransportTypes();
4419 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4420 return false;
4421 }
4422 try {
4423 mContext.enforceCallingOrSelfPermission(
4424 android.Manifest.permission.ACCESS_WIFI_STATE,
4425 "ConnectivityService");
4426 } catch (SecurityException e) {
4427 return false;
4428 }
4429 return true;
4430 }
4431
Robert Greenwalt9258c642014-03-26 16:47:06 -07004432 @Override
4433 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4434 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004435 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4436 enforceAccessPermission();
4437 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004439 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004440 ensureSufficientPermissionsForRequest(networkCapabilities,
4441 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004442 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004443 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4444 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4445 // onLost and onAvailable callbacks when networks move in and out of the background.
4446 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4447 // can't request networks.
4448 restrictBackgroundRequestForCaller(nc);
4449 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004450
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004451 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004452 NetworkRequest.Type.LISTEN);
4453 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004454 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004455
4456 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4457 return networkRequest;
4458 }
4459
4460 @Override
4461 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4462 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004463 checkNotNull(operation, "PendingIntent cannot be null.");
4464 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4465 enforceAccessPermission();
4466 }
Etan Cohen859748f2017-04-03 17:42:34 -07004467 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004468 ensureSufficientPermissionsForRequest(networkCapabilities,
4469 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004470
Chalard Jeandda156a2018-01-10 21:19:32 +09004471 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004472 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004473
4474 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004475 NetworkRequest.Type.LISTEN);
4476 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004477 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004478
4479 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004480 }
4481
Erik Klineacdd6392016-07-07 16:50:58 +09004482 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004483 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004484 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004485 mHandler.sendMessage(mHandler.obtainMessage(
4486 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004487 }
4488
4489 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004490 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004491 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004492 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4493 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004494 }
4495
Robert Greenwalta67be032014-05-16 15:49:14 -07004496 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004497 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004498 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4499 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4500 }
4501
4502 @Override
4503 public void unregisterNetworkFactory(Messenger messenger) {
4504 enforceConnectivityInternalPermission();
4505 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4506 }
4507
4508 private void handleUnregisterNetworkFactory(Messenger messenger) {
4509 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4510 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004512 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004513 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004514 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004515 }
4516
Robert Greenwalt7b816022014-04-18 15:25:25 -07004517 /**
4518 * NetworkAgentInfo supporting a request by requestId.
4519 * These have already been vetted (their Capabilities satisfy the request)
4520 * and the are the highest scored network available.
4521 * the are keyed off the Requests requestId.
4522 */
Hugo Benichicd952782017-09-20 11:20:14 +09004523 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4524 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004525 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526
Paul Jensen31a94f42015-02-13 14:18:39 -05004527 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4528 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004529 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004530 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4531 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4532 // there may not be a strict 1:1 correlation between the two.
4533 @GuardedBy("mNetworkForNetId")
4534 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 // NetworkAgentInfo keyed off its connecting messenger
4537 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004538 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004539 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004541 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004542 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004543
Paul Jensen2c311d62014-11-17 12:34:51 -05004544 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004546
Erik Klineda4bfa82015-04-30 12:58:40 +09004547 // Request used to optionally keep mobile data active even when higher
4548 // priority networks like Wi-Fi are active.
4549 private final NetworkRequest mDefaultMobileDataRequest;
4550
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004551 // Request used to optionally keep wifi data active even when higher
4552 // priority networks like ethernet are active.
4553 private final NetworkRequest mDefaultWifiRequest;
4554
Hugo Benichicd952782017-09-20 11:20:14 +09004555 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4556 synchronized (mNetworkForRequestId) {
4557 return mNetworkForRequestId.get(requestId);
4558 }
4559 }
4560
4561 private void clearNetworkForRequest(int requestId) {
4562 synchronized (mNetworkForRequestId) {
4563 mNetworkForRequestId.remove(requestId);
4564 }
4565 }
4566
4567 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4568 synchronized (mNetworkForRequestId) {
4569 mNetworkForRequestId.put(requestId, nai);
4570 }
4571 }
4572
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004573 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004574 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004575 }
4576
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004577 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004578 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004579 }
4580
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004581 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4582 return nri.request.requestId == mDefaultRequest.requestId;
4583 }
4584
Paul Jensen31a94f42015-02-13 14:18:39 -05004585 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004587 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004588 enforceConnectivityInternalPermission();
4589
Rubin Xu1bb5c082017-09-05 18:40:49 +01004590 LinkProperties lp = new LinkProperties(linkProperties);
4591 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004592 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4593 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004594 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004595 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004596 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004597 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004598 // Make sure the network capabilities reflect what the agent info says.
4599 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004600 synchronized (this) {
4601 nai.networkMonitor.systemReady = mSystemReady;
4602 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004603 final String extraInfo = networkInfo.getExtraInfo();
4604 final String name = TextUtils.isEmpty(extraInfo)
4605 ? nai.networkCapabilities.getSSID() : extraInfo;
4606 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004607 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004609 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004610 }
4611
Erik Klinee5dac902018-03-04 21:01:01 +09004612 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004613 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004614 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004615 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004616 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004617 }
Erik Klinee5dac902018-03-04 21:01:01 +09004618 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4619 NetworkInfo networkInfo = nai.networkInfo;
4620 nai.networkInfo = null;
4621 updateNetworkInfo(nai, networkInfo);
4622 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004623 }
4624
4625 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004626 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 int netId = networkAgent.network.netId;
4628
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004629 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4630 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004631 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004632 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004633 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004634
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004635 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004636 updateMtu(newLp, oldLp);
4637 // TODO - figure out what to do for clat
4638// for (LinkProperties lp : newLp.getStackedLinks()) {
4639// updateMtu(lp, null);
4640// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004641 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004642
Erik Kline94887872016-04-05 13:30:49 +09004643 updateRoutes(newLp, oldLp, netId);
4644 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004645 // Make sure LinkProperties represents the latest private DNS status.
4646 // This does not need to be done before updateDnses because the
4647 // LinkProperties are not the source of the private DNS configuration.
4648 // updateDnses will fetch the private DNS configuration from DnsManager.
4649 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004650
Hugo Benichi6f62b732017-06-27 15:13:20 +09004651 // Start or stop clat accordingly to network state.
Luke Huang4e25ec62018-09-27 16:58:23 +08004652 networkAgent.updateClat(mNMS);
Paul Jensene0bef712014-12-10 15:12:18 -05004653 if (isDefaultNetwork(networkAgent)) {
4654 handleApplyDefaultProxy(newLp.getHttpProxy());
4655 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004656 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004657 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004658 // TODO - move this check to cover the whole function
4659 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004660 synchronized (networkAgent) {
4661 networkAgent.linkProperties = newLp;
4662 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004663 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004664 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4665 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004666
4667 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004668 }
4669
Joel Scherpelz668370b2017-06-08 15:35:21 +09004670 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004671 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004672 // marks on unsupported interfaces is harmless.
4673 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4674 return;
4675 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004676
Joel Scherpelz668370b2017-06-08 15:35:21 +09004677 int mark = mContext.getResources().getInteger(
4678 com.android.internal.R.integer.config_networkWakeupPacketMark);
4679 int mask = mContext.getResources().getInteger(
4680 com.android.internal.R.integer.config_networkWakeupPacketMask);
4681
4682 // Mask/mark of zero will not detect anything interesting.
4683 // Don't install rules unless both values are nonzero.
4684 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004685 return;
4686 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004687
4688 final String prefix = "iface:" + iface;
4689 try {
4690 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08004691 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004692 } else {
Luke Huang674660f2018-09-27 19:33:11 +08004693 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004694 }
4695 } catch (Exception e) {
4696 loge("Exception modifying wakeup packet monitoring: " + e);
4697 }
4698
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004699 }
4700
4701 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4702 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004703 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004704 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4705 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004706 for (String iface : interfaceDiff.added) {
4707 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004708 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08004709 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004710 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004711 } catch (Exception e) {
4712 loge("Exception adding interface: " + e);
4713 }
4714 }
4715 for (String iface : interfaceDiff.removed) {
4716 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004717 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004718 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08004719 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004720 } catch (Exception e) {
4721 loge("Exception removing interface: " + e);
4722 }
4723 }
4724 }
4725
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004726 /**
4727 * Have netd update routes from oldLp to newLp.
4728 * @return true if routes changed between oldLp and newLp
4729 */
4730 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004731 // Compare the route diff to determine which routes should be added and removed.
4732 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4733 oldLp != null ? oldLp.getAllRoutes() : null,
4734 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004735
4736 // add routes before removing old in case it helps with continuous connectivity
4737
Chalard Jean4d660112018-06-04 16:52:49 +09004738 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004739 for (RouteInfo route : routeDiff.added) {
4740 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004741 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004742 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004743 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004744 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004745 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4746 loge("Exception in addRoute for non-gateway: " + e);
4747 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004748 }
4749 }
4750 for (RouteInfo route : routeDiff.added) {
4751 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004752 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004753 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004754 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004755 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004756 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4757 loge("Exception in addRoute for gateway: " + e);
4758 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 }
4760 }
4761
4762 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004763 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004764 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004765 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 } catch (Exception e) {
4767 loge("Exception in removeRoute: " + e);
4768 }
4769 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004770 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004771 }
Erik Kline41368502015-06-17 13:19:54 +09004772
Erik Kline94887872016-04-05 13:30:49 +09004773 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4774 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4775 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004776 }
Erik Kline94887872016-04-05 13:30:49 +09004777
Erik Kline1742fe12017-12-13 19:40:49 +09004778 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4779 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4780
Erik Klinea24d4592018-01-11 21:07:29 +09004781 if (DBG) {
4782 final Collection<InetAddress> dnses = newLp.getDnsServers();
4783 log("Setting DNS servers for network " + netId + " to " + dnses);
4784 }
Erik Kline94887872016-04-05 13:30:49 +09004785 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004786 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004787 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004788 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004789 }
Erik Kline4edba012017-04-07 15:29:29 +09004790 }
4791
Luke Huang8a462ec2018-08-24 20:33:16 +08004792 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004793 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08004794 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004795 }
4796 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08004797 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004798 }
Luke Huang8a462ec2018-08-24 20:33:16 +08004799 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004800 }
4801
Paul Jensen3d194ea2015-06-16 14:27:36 -04004802 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004803 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4804 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4805 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004806 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004807 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004808 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004809 // Don't complain for VPNs since they're not driven by requests and there is no risk of
4810 // causing a connect/teardown loop.
4811 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
4812 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004813 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004814 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004815 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4816 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004817 // does not cause any request (that is not a listen) currently matching that agent to
4818 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004820 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004821 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004822 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823 }
4824
Paul Jensen3d194ea2015-06-16 14:27:36 -04004825 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004827 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004828 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004829 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004830 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004831 }
Paul Jensene0988542015-06-25 15:30:08 -04004832 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004834 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004835 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004836 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004837 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004838 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004839 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004840 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004841 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004842 if (nai.isSuspended()) {
4843 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4844 } else {
4845 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4846 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004847
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004848 return newNc;
4849 }
4850
4851 /**
4852 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4853 *
4854 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4855 * capabilities we manage and store in {@code nai}, such as validated status and captive
4856 * portal status)
4857 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4858 * potentially triggers rematches.
4859 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4860 * change.)
4861 *
4862 * @param oldScore score of the network before any of the changes that prompted us
4863 * to call this function.
4864 * @param nai the network having its capabilities updated.
4865 * @param nc the new network capabilities.
4866 */
4867 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4868 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4869
4870 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004871
Luke Huang8a462ec2018-08-24 20:33:16 +08004872 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
4873 final int newPermission = getNetworkPermission(newNc);
4874 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004875 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004876 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877 } catch (RemoteException e) {
4878 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004879 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004880 }
4881
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004882 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004884 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004885 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004886 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004887
Chalard Jeanf213ca12018-01-16 18:43:05 +09004888 updateUids(nai, prevNc, newNc);
4889
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004890 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004891 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4892 // the change we're processing can't affect any requests, it can only affect the listens
4893 // on this network. We might have been called by rematchNetworkAndRequests when a
4894 // network changed foreground state.
4895 processListenRequests(nai, true);
4896 } else {
4897 // If the requestable capabilities have changed or the score changed, we can't have been
4898 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004899 rematchAllNetworksAndRequests(nai, oldScore);
4900 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004901 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004902
4903 // Report changes that are interesting for network statistics tracking.
4904 if (prevNc != null) {
4905 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004906 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004907 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004908 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004909 if (meteredChanged || roamingChanged) {
4910 notifyIfacesChangedForNetworkStats();
4911 }
4912 }
4913
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004914 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004915 // Tell VPNs about updated capabilities, since they may need to
4916 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004917 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004918 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004919 }
4920
Chalard Jeanf213ca12018-01-16 18:43:05 +09004921 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4922 NetworkCapabilities newNc) {
4923 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4924 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4925 if (null == prevRanges) prevRanges = new ArraySet<>();
4926 if (null == newRanges) newRanges = new ArraySet<>();
4927 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4928
4929 prevRanges.removeAll(newRanges);
4930 newRanges.removeAll(prevRangesCopy);
4931
4932 try {
4933 if (!newRanges.isEmpty()) {
4934 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4935 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08004936 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004937 }
4938 if (!prevRanges.isEmpty()) {
4939 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4940 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08004941 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004942 }
4943 } catch (Exception e) {
4944 // Never crash!
4945 loge("Exception in updateUids: " + e);
4946 }
4947 }
4948
Hugo Benichief502882017-09-01 01:23:32 +00004949 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004950 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004951 // Ignore updates for disconnected networks
4952 return;
4953 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004954 // newLp is already a defensive copy.
4955 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004956 if (VDBG) {
4957 log("Update of LinkProperties for " + nai.name() +
4958 "; created=" + nai.created +
4959 "; everConnected=" + nai.everConnected);
4960 }
4961 LinkProperties oldLp = nai.linkProperties;
4962 synchronized (nai) {
4963 nai.linkProperties = newLp;
4964 }
4965 if (nai.everConnected) {
4966 updateLinkProperties(nai, oldLp);
4967 }
4968 }
4969
Paul Jensenc8b9a742014-09-30 15:37:41 -04004970 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004971 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4972 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004973 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004974 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004975 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4976 }
4977 }
4978
Robert Greenwalt7b816022014-04-18 15:25:25 -07004979 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4980 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004981 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004982 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4983 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004984 }
4985 }
4986
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004987 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4988 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004989 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004990 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004991 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4992 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004993 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004994 sendIntent(nri.mPendingIntent, intent);
4995 }
4996 // else not handled
4997 }
4998
4999 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5000 mPendingIntentWakeLock.acquire();
5001 try {
5002 if (DBG) log("Sending " + pendingIntent);
5003 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5004 } catch (PendingIntent.CanceledException e) {
5005 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5006 mPendingIntentWakeLock.release();
5007 releasePendingNetworkRequest(pendingIntent);
5008 }
5009 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5010 }
5011
5012 @Override
5013 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5014 String resultData, Bundle resultExtras) {
5015 if (DBG) log("Finished sending " + pendingIntent);
5016 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005017 // Release with a delay so the receiving client has an opportunity to put in its
5018 // own request.
5019 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005020 }
5021
Chalard Jeanf19db372018-01-26 19:24:40 +09005022 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005023 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005024 if (nri.messenger == null) {
5025 return; // Default request has no msgr
5026 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005027 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005028 // TODO: check if defensive copies of data is needed.
5029 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005030 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005031 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5032 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005033 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005034 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005035 case ConnectivityManager.CALLBACK_AVAILABLE: {
5036 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5037 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5038 break;
5039 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005040 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005041 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005042 break;
5043 }
5044 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005045 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005046 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005047 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005048 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005049 break;
5050 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005051 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005052 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005053 break;
5054 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005055 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005056 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005057 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005058 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005059 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005060 String notification = ConnectivityManager.getCallbackName(notificationType);
5061 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005062 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005063 nri.messenger.send(msg);
5064 } catch (RemoteException e) {
5065 // may occur naturally in the race of binder death.
5066 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5067 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 }
5069
Hugo Benichidba33db2017-03-23 22:40:44 +09005070 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5071 bundle.putParcelable(t.getClass().getSimpleName(), t);
5072 }
5073
Paul Jensenc8b9a742014-09-30 15:37:41 -04005074 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005075 if (nai.numRequestNetworkRequests() != 0) {
5076 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5077 NetworkRequest nr = nai.requestAt(i);
5078 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005079 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005080 loge("Dead network still had at least " + nr);
5081 break;
5082 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005083 }
5084 nai.asyncChannel.disconnect();
5085 }
5086
Robert Greenwalt7b816022014-04-18 15:25:25 -07005087 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5088 if (oldNetwork == null) {
5089 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5090 return;
5091 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005092 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005093
5094 // If we get here it means that the last linger timeout for this network expired. So there
5095 // must be no other active linger timers, and we must stop lingering.
5096 oldNetwork.clearLingerState();
5097
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005098 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005099 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005100 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005101 } else {
5102 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005103 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5104 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 }
5107
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005108 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005109 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005110
Paul Jensen27b02b72014-07-14 12:03:33 -04005111 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005112 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005113 } catch (Exception e) {
5114 loge("Exception setting default network :" + e);
5115 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005116
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005117 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005118 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005119 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005120 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005121 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005122 }
5123
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005124 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005125 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5126 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5127 NetworkRequest nr = nri.request;
5128 if (!nr.isListen()) continue;
5129 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5130 nai.removeRequest(nri.request.requestId);
5131 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5132 }
5133 }
5134
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005135 if (capabilitiesChanged) {
5136 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5137 }
5138
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005139 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5140 NetworkRequest nr = nri.request;
5141 if (!nr.isListen()) continue;
5142 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5143 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005144 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005145 }
5146 }
5147 }
5148
Paul Jensen2161a8e2014-09-11 11:00:39 -04005149 // Handles a network appearing or improving its score.
5150 //
5151 // - Evaluates all current NetworkRequests that can be
5152 // satisfied by newNetwork, and reassigns to newNetwork
5153 // any such requests for which newNetwork is the best.
5154 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005155 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005156 // needed. A network is needed if it is the best network for
5157 // one or more NetworkRequests, or if it is a VPN.
5158 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005159 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005160 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005161 //
5162 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5163 // networks that have no chance (i.e. even if validated)
5164 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005165 //
5166 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5167 // it does not remove NetworkRequests that other Networks could better satisfy.
5168 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5169 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5170 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005171 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005172 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005173 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5174 // performed to tear down unvalidated networks that have no chance (i.e. even if
5175 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005176 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005177 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005178 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005179 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005180 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005181 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005182
5183 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5184 final int score = newNetwork.getCurrentScore();
5185
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005186 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005187
Paul Jensen2161a8e2014-09-11 11:00:39 -04005188 // Find and migrate to this Network any NetworkRequests for
5189 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005190 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5191 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005192 NetworkCapabilities nc = newNetwork.networkCapabilities;
5193 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005194 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005195 // Process requests in the first pass and listens in the second pass. This allows us to
5196 // change a network's capabilities depending on which requests it has. This is only
5197 // correct if the change in capabilities doesn't affect whether the network satisfies
5198 // requests or not, and doesn't affect the network's score.
5199 if (nri.request.isListen()) continue;
5200
Hugo Benichicd952782017-09-20 11:20:14 +09005201 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005202 final boolean satisfies = newNetwork.satisfies(nri.request);
5203 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005204 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005205 log("Network " + newNetwork.name() + " was already satisfying" +
5206 " request " + nri.request.requestId + ". No change.");
5207 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005208 keep = true;
5209 continue;
5210 }
5211
5212 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005213 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005214 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 // next check if it's better than any current network we're using for
5216 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005217 if (VDBG) {
5218 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005219 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005220 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005221 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005222 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005223 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005224 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005225 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005226 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005227 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005228 affectedNetworks.add(currentNetwork);
5229 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005230 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005231 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005232 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005233 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005234 if (!newNetwork.addRequest(nri.request)) {
5235 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5236 }
5237 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005238 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005239 // Tell NetworkFactories about the new score, so they can stop
5240 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005241 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 // network. Think about if there is a way to reduce this. Push
5243 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005244 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005245 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005246 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005247 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005248 if (currentNetwork != null) {
5249 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005251 }
5252 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005253 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005254 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5255 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005256 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005257 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5258 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5259 // This means this code doesn't have to handle the case where "currentNetwork" no
5260 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5261 if (DBG) {
5262 log("Network " + newNetwork.name() + " stopped satisfying" +
5263 " request " + nri.request.requestId);
5264 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005265 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005266 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005267 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005268 sendUpdatedScoreToFactories(nri.request, 0);
5269 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005270 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5271 newNetwork.name() +
5272 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005273 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005274 // TODO: Technically, sending CALLBACK_LOST here is
5275 // incorrect if there is a replacement network currently
5276 // connected that can satisfy nri, which is a request
5277 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005278 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5279 // so this code is only incorrect for a network that loses
5280 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005281 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005282 }
5283 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005285 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005286 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005287 makeDefault(newNetwork);
5288 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005289 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005290 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005291 // Have a new default network, release the transition wakelock in
5292 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005293 }
5294
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005295 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5296 Slog.wtf(TAG, String.format(
5297 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005298 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005299 }
5300 if (newNetwork.getCurrentScore() != score) {
5301 Slog.wtf(TAG, String.format(
5302 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005303 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005304 }
5305
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005306 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005307 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5308 // If the network went from background to foreground or vice versa, we need to update
5309 // its foreground state. It is safe to do this after rematching the requests because
5310 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5311 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005312 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005313 } else {
5314 processListenRequests(newNetwork, false);
5315 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005316
Paul Jensencf4c2c62015-07-01 14:16:32 -04005317 // do this after the default net is switched, but
5318 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005319 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005320
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005321 // Linger any networks that are no longer needed. This should be done after sending the
5322 // available callback for newNetwork.
5323 for (NetworkAgentInfo nai : affectedNetworks) {
5324 updateLingerState(nai, now);
5325 }
5326 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5327 // does not need to be done in any particular order.
5328 updateLingerState(newNetwork, now);
5329
Paul Jensencf4c2c62015-07-01 14:16:32 -04005330 if (isNewDefault) {
5331 // Maintain the illusion: since the legacy API only
5332 // understands one network at a time, we must pretend
5333 // that the current default network disconnected before
5334 // the new one connected.
5335 if (oldDefaultNetwork != null) {
5336 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5337 oldDefaultNetwork, true);
5338 }
5339 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5340 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5341 notifyLockdownVpn(newNetwork);
5342 }
5343
Robert Greenwalt7b816022014-04-18 15:25:25 -07005344 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005345 // Notify battery stats service about this network, both the normal
5346 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005347 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005348 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005349 final IBatteryStats bs = BatteryStatsService.getService();
5350 final int type = newNetwork.networkInfo.getType();
5351
5352 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5353 bs.noteNetworkInterfaceType(baseIface, type);
5354 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5355 final String stackedIface = stacked.getInterfaceName();
5356 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005357 }
5358 } catch (RemoteException ignored) {
5359 }
5360
Robert Greenwalt152ed372014-12-17 17:19:53 -08005361 // This has to happen after the notifyNetworkCallbacks as that tickles each
5362 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005363 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005364 // and will generally do a dns request so they can ensureRouteToHost and if
5365 // they do that before the callbacks happen they'll use the default network.
5366 //
5367 // TODO: Is there still a race here? We send the broadcast
5368 // after sending the callback, but if the app can receive the
5369 // broadcast before the callback, it might still break.
5370 //
5371 // This *does* introduce a race where if the user uses the new api
5372 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5373 // they may get old info. Reverse this after the old startUsing api is removed.
5374 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005375 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5376 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005377 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005378 // legacy type tracker filters out repeat adds
5379 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5380 }
5381 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005382
5383 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5384 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5385 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5386 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5387 if (newNetwork.isVPN()) {
5388 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005390 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005391 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5392 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005393 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005394 if (nai.getLingerExpiry() > 0) {
5395 // This network has active linger timers and no requests, but is not
5396 // lingering. Linger it.
5397 //
5398 // One way (the only way?) this can happen if this network is unvalidated
5399 // and became unneeded due to another network improving its score to the
5400 // point where this network will no longer be able to satisfy any requests
5401 // even if it validates.
5402 updateLingerState(nai, now);
5403 } else {
5404 if (DBG) log("Reaping " + nai.name());
5405 teardownUnneededNetwork(nai);
5406 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005407 }
5408 }
5409 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005410 }
5411
Paul Jensen1c7ba022015-06-16 14:27:36 -04005412 /**
5413 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5414 * being disconnected.
5415 * @param changed If only one Network's score or capabilities have been modified since the last
5416 * time this function was called, pass this Network in this argument, otherwise pass
5417 * null.
5418 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5419 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5420 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5421 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5422 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005423 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005424 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005425 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5426 // to avoid the slowness. It is not simply enough to process just "changed", for
5427 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005428 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005429
5430 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5431 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5432 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005433 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005434 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005435 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005436 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005437 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5438 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5439 // Rematch higher scoring networks first to prevent requests first matching a lower
5440 // scoring network and then a higher scoring network, which could produce multiple
5441 // callbacks and inadvertently unlinger networks.
5442 Arrays.sort(nais);
5443 for (NetworkAgentInfo nai : nais) {
5444 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005445 // Only reap the last time through the loop. Reaping before all rematching
5446 // is complete could incorrectly teardown a network that hasn't yet been
5447 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005448 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005449 : ReapUnvalidatedNetworks.REAP,
5450 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005451 }
5452 }
5453 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005454
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005455 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005456 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005457 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005458 // For now only update icons for default connection.
5459 // TODO: Update WiFi and cellular icons separately. b/17237507
5460 if (!isDefaultNetwork(nai)) return;
5461
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005462 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005463 // Don't repeat publish.
5464 if (newInetCondition == mDefaultInetConditionPublished) return;
5465
5466 mDefaultInetConditionPublished = newInetCondition;
5467 sendInetConditionBroadcast(nai.networkInfo);
5468 }
5469
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005470 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005471 synchronized (mVpns) {
5472 if (mLockdownTracker != null) {
5473 if (nai != null && nai.isVPN()) {
5474 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5475 } else {
5476 mLockdownTracker.onNetworkInfoChanged();
5477 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005478 }
5479 }
5480 }
5481
Robert Greenwalt7b816022014-04-18 15:25:25 -07005482 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005483 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005484 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005485 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005486 synchronized (networkAgent) {
5487 oldInfo = networkAgent.networkInfo;
5488 networkAgent.networkInfo = newInfo;
5489 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005490 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005491
Robert Greenwalt7b816022014-04-18 15:25:25 -07005492 if (DBG) {
5493 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5494 (oldInfo == null ? "null" : oldInfo.getState()) +
5495 " to " + state);
5496 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005497
Robin Lee585e2482016-05-01 23:00:00 +01005498 if (!networkAgent.created
5499 && (state == NetworkInfo.State.CONNECTED
5500 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005501
5502 // A network that has just connected has zero requests and is thus a foreground network.
5503 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5504
Robert Greenwalt7b816022014-04-18 15:25:25 -07005505 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005506 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005507 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08005508 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005509 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5510 (networkAgent.networkMisc == null ||
5511 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005512 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08005513 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005514 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005515 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005516 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005517 loge("Error creating network " + networkAgent.network.netId + ": "
5518 + e.getMessage());
5519 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005520 }
Paul Jenseneec75412014-08-04 12:21:19 -04005521 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005522 }
5523
5524 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5525 networkAgent.everConnected = true;
5526
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005527 if (networkAgent.linkProperties == null) {
5528 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5529 }
5530
Erik Kline736353a2018-03-21 07:18:33 -07005531 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005532 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005533
Paul Jensenca8f16a2014-05-09 12:47:55 -04005534 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005535 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005536
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005537 if (networkAgent.isVPN()) {
5538 // Temporarily disable the default proxy (not global).
Chalard Jean52c2aa72018-06-07 16:44:04 +09005539 synchronized (mProxyTracker.mProxyLock) {
5540 if (!mProxyTracker.mDefaultProxyDisabled) {
5541 mProxyTracker.mDefaultProxyDisabled = true;
5542 if (mProxyTracker.mGlobalProxy == null
5543 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005544 mProxyTracker.sendProxyBroadcast(null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005545 }
5546 }
5547 }
5548 // TODO: support proxy per network.
5549 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005550
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005551 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5552 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5553 // capabilities, so it only needs to be done once on initial connect, not every time the
5554 // network's capabilities change. Note that we do this before rematching the network,
5555 // so we could decide to tear it down immediately afterwards. That's fine though - on
5556 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5557 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005558 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005559
Paul Jensen2161a8e2014-09-11 11:00:39 -04005560 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005561 final long now = SystemClock.elapsedRealtime();
5562 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005563
5564 // This has to happen after matching the requests, because callbacks are just requests.
5565 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005566 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005567 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005568 if (networkAgent.isVPN()) {
Chalard Jean52c2aa72018-06-07 16:44:04 +09005569 synchronized (mProxyTracker.mProxyLock) {
5570 if (mProxyTracker.mDefaultProxyDisabled) {
5571 mProxyTracker.mDefaultProxyDisabled = false;
5572 if (mProxyTracker.mGlobalProxy == null
5573 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005574 mProxyTracker.sendProxyBroadcast(mProxyTracker.mDefaultProxy);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005575 }
5576 }
5577 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005578 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005579 }
Chalard Jean392971c2018-05-11 20:19:20 +09005580 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005581 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5582 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005583 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005584 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005585 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005586 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005587 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5588 networkAgent.networkCapabilities);
5589 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5590 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005591 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5592 ConnectivityManager.CALLBACK_SUSPENDED :
5593 ConnectivityManager.CALLBACK_RESUMED));
5594 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005595 }
5596 }
5597
Robert Greenwaltac96c522014-06-03 16:43:57 -07005598 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005599 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005600 if (score < 0) {
5601 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5602 "). Bumping score to min of 0");
5603 score = 0;
5604 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005605
Paul Jensen2161a8e2014-09-11 11:00:39 -04005606 final int oldScore = nai.getCurrentScore();
5607 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005608
Paul Jensen85cf78e2015-06-25 13:25:07 -04005609 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005610
Paul Jensenc8b9a742014-09-30 15:37:41 -04005611 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005612 }
5613
Erik Klinec75d4fa2017-02-15 19:59:17 +09005614 // Notify only this one new request of the current state. Transfer all the
5615 // current state by calling NetworkCapabilities and LinkProperties callbacks
5616 // so that callers can be guaranteed to have as close to atomicity in state
5617 // transfer as can be supported by this current API.
5618 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005619 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005620 if (nri.mPendingIntent != null) {
5621 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5622 // Attempt no subsequent state pushes where intents are involved.
5623 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005624 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005625
5626 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005627 }
5628
Robert Greenwalt8d482522015-06-24 13:23:42 -07005629 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005630 // The NetworkInfo we actually send out has no bearing on the real
5631 // state of affairs. For example, if the default connection is mobile,
5632 // and a request for HIPRI has just gone away, we need to pretend that
5633 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5634 // the state to DISCONNECTED, even though the network is of type MOBILE
5635 // and is still connected.
5636 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5637 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005638 if (state != DetailedState.DISCONNECTED) {
5639 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005640 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005641 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005642 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005643 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5644 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5646 if (info.isFailover()) {
5647 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5648 nai.networkInfo.setFailover(false);
5649 }
5650 if (info.getReason() != null) {
5651 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5652 }
5653 if (info.getExtraInfo() != null) {
5654 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5655 }
5656 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005657 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005658 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005659 if (newDefaultAgent != null) {
5660 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5661 newDefaultAgent.networkInfo);
5662 } else {
5663 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5664 }
5665 }
5666 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5667 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005668 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005669 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005670 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005671 }
5672 }
5673 }
5674
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005675 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005676 if (VDBG) {
5677 String notification = ConnectivityManager.getCallbackName(notifyType);
5678 log("notifyType " + notification + " for " + networkAgent.name());
5679 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005680 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5681 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005682 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5683 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005684 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5685 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005686 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005687 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005688 } else {
5689 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5690 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005691 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005692 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005693
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005694 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5695 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5696 }
5697
Jeff Sharkey69736342014-12-08 14:50:12 -08005698 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005699 * Returns the list of all interfaces that could be used by network traffic that does not
5700 * explicitly specify a network. This includes the default network, but also all VPNs that are
5701 * currently connected.
5702 *
5703 * Must be called on the handler thread.
5704 */
5705 private Network[] getDefaultNetworks() {
5706 ArrayList<Network> defaultNetworks = new ArrayList<>();
5707 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5708 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5709 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5710 defaultNetworks.add(nai.network);
5711 }
5712 }
5713 return defaultNetworks.toArray(new Network[0]);
5714 }
5715
5716 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005717 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5718 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005719 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005720 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005721 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005722 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005723 } catch (Exception ignored) {
5724 }
5725 }
5726
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005727 @Override
5728 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005729 int user = UserHandle.getUserId(Binder.getCallingUid());
5730 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005731 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005732 return mVpns.get(user).addAddress(address, prefixLength);
5733 }
5734 }
5735
5736 @Override
5737 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005738 int user = UserHandle.getUserId(Binder.getCallingUid());
5739 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005740 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005741 return mVpns.get(user).removeAddress(address, prefixLength);
5742 }
5743 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005744
5745 @Override
5746 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005747 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005748 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005749 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005750 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005751 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005752 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005753 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005754 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005755 }
5756 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005757 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005758
5759 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005760 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005761 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005762 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005763 }
5764
5765 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005766 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5767 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5768 enforceKeepalivePermission();
5769 mKeepaliveTracker.startNattKeepalive(
5770 getNetworkAgentInfoForNetwork(network),
5771 intervalSeconds, messenger, binder,
5772 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5773 }
5774
5775 @Override
5776 public void stopKeepalive(Network network, int slot) {
5777 mHandler.sendMessage(mHandler.obtainMessage(
5778 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5779 }
5780
5781 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005782 public void factoryReset() {
5783 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005784
5785 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5786 return;
5787 }
5788
Robin Lee3b3dd942015-05-12 18:14:58 +01005789 final int userId = UserHandle.getCallingUserId();
5790
Stuart Scottf1fb3972015-04-02 18:00:02 -07005791 // Turn airplane mode off
5792 setAirplaneMode(false);
5793
Stuart Scotte3e314d2015-04-20 14:07:45 -07005794 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5795 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005796 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005797 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005798 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005799 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005800 }
5801
Stuart Scotte3e314d2015-04-20 14:07:45 -07005802 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005803 // Remove always-on package
5804 synchronized (mVpns) {
5805 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5806 if (alwaysOnPackage != null) {
5807 setAlwaysOnVpnPackage(userId, null, false);
5808 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5809 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005810
Hugo Benichi69744342017-11-27 10:57:16 +09005811 // Turn Always-on VPN off
5812 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5813 final long ident = Binder.clearCallingIdentity();
5814 try {
5815 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5816 mLockdownEnabled = false;
5817 setLockdownTracker(null);
5818 } finally {
5819 Binder.restoreCallingIdentity(ident);
5820 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005821 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005822
Hugo Benichi69744342017-11-27 10:57:16 +09005823 // Turn VPN off
5824 VpnConfig vpnConfig = getVpnConfig(userId);
5825 if (vpnConfig != null) {
5826 if (vpnConfig.legacy) {
5827 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5828 } else {
5829 // Prevent this app (packagename = vpnConfig.user) from initiating
5830 // VPN connections in the future without user intervention.
5831 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005832
Hugo Benichi69744342017-11-27 10:57:16 +09005833 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5834 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005835 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005836 }
5837 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005838
5839 Settings.Global.putString(mContext.getContentResolver(),
5840 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005841 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005842
Ricky Wai44dcbde2018-01-23 04:09:45 +00005843 @Override
5844 public byte[] getNetworkWatchlistConfigHash() {
5845 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5846 if (nwm == null) {
5847 loge("Unable to get NetworkWatchlistManager");
5848 return null;
5849 }
5850 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5851 return nwm.getWatchlistConfigHash();
5852 }
5853
Paul Jensencf4c2c62015-07-01 14:16:32 -04005854 @VisibleForTesting
5855 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5856 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5857 return new NetworkMonitor(context, handler, nai, defaultRequest);
5858 }
Erik Kline48f12f22016-04-14 17:30:59 +09005859
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005860 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005861 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5862 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005863 }
5864
5865 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005866 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5867 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5868 }
5869
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005870 @VisibleForTesting
5871 public boolean hasService(String name) {
5872 return ServiceManager.checkService(name) != null;
5873 }
5874
Hugo Benichi64901e52017-10-19 14:42:40 +09005875 @VisibleForTesting
5876 protected IpConnectivityMetrics.Logger metricsLogger() {
5877 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5878 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005879 }
5880
5881 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005882 int[] transports = nai.networkCapabilities.getTransportTypes();
5883 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005884 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005885
5886 private static boolean toBool(int encodedBoolean) {
5887 return encodedBoolean != 0; // Only 0 means false.
5888 }
5889
5890 private static int encodeBool(boolean b) {
5891 return b ? 1 : 0;
5892 }
mswest46386886f2018-03-12 10:34:34 -07005893
5894 @Override
5895 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5896 FileDescriptor err, String[] args, ShellCallback callback,
5897 ResultReceiver resultReceiver) {
5898 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5899 }
5900
5901 private class ShellCmd extends ShellCommand {
5902
5903 @Override
5904 public int onCommand(String cmd) {
5905 if (cmd == null) {
5906 return handleDefaultCommands(cmd);
5907 }
5908 final PrintWriter pw = getOutPrintWriter();
5909 try {
5910 switch (cmd) {
5911 case "airplane-mode":
5912 final String action = getNextArg();
5913 if ("enable".equals(action)) {
5914 setAirplaneMode(true);
5915 return 0;
5916 } else if ("disable".equals(action)) {
5917 setAirplaneMode(false);
5918 return 0;
5919 } else if (action == null) {
5920 final ContentResolver cr = mContext.getContentResolver();
5921 final int enabled = Settings.Global.getInt(cr,
5922 Settings.Global.AIRPLANE_MODE_ON);
5923 pw.println(enabled == 0 ? "disabled" : "enabled");
5924 return 0;
5925 } else {
5926 onHelp();
5927 return -1;
5928 }
5929 default:
5930 return handleDefaultCommands(cmd);
5931 }
5932 } catch (Exception e) {
5933 pw.println(e);
5934 }
5935 return -1;
5936 }
5937
5938 @Override
5939 public void onHelp() {
5940 PrintWriter pw = getOutPrintWriter();
5941 pw.println("Connectivity service commands:");
5942 pw.println(" help");
5943 pw.println(" Print this help text.");
5944 pw.println(" airplane-mode [enable|disable]");
5945 pw.println(" Turn airplane mode on or off.");
5946 pw.println(" airplane-mode");
5947 pw.println(" Get airplane mode.");
5948 }
5949 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07005950
5951 /**
5952 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
5953 * for testing.
5954 */
5955 private Vpn enforceActiveVpnOrNetworkStackPermission() {
5956 if (checkNetworkStackPermission()) {
5957 return null;
5958 }
5959 final int uid = Binder.getCallingUid();
5960 final int user = UserHandle.getUserId(uid);
5961 synchronized (mVpns) {
5962 Vpn vpn = mVpns.get(user);
5963 try {
5964 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
5965 } catch (NullPointerException e) {
5966 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
5967 }
5968 }
5969 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
5970 + "permission");
5971 }
5972
5973 /**
5974 * @param connectionInfo the connection to resolve.
5975 * @return {@code uid} if the connection is found and the app has permission to observe it
5976 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
5977 * connection is not found.
5978 */
5979 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
5980 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
5981 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
5982 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
5983 }
5984
5985 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
5986 connectionInfo.local, connectionInfo.remote);
5987
5988 /* Filter out Uids not associated with the VPN. */
5989 if (vpn != null && !vpn.appliesToUid(uid)) {
5990 return INVALID_UID;
5991 }
5992
5993 return uid;
5994 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005995}