blob: 60a9ba4ac7ba1583758062b90580f2eb0e57c5f9 [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 /**
396 * used internally to (re)configure mobile data always-on settings.
397 */
398 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
399
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
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900754 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900755 mHandlerThread.start();
756 mHandler = new InternalHandler(mHandlerThread.getLooper());
757 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700758
Jeremy Joslin79294842014-12-03 17:15:28 -0800759 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
760 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
761
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900762 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900763
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700764 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800765 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800766 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700767 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900768 mPolicyManagerInternal = checkNotNull(
769 LocalServices.getService(NetworkPolicyManagerInternal.class),
770 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900771 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900772
Luke Huang674660f2018-09-27 19:33:11 +0800773 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700774 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700775 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700776
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700777 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900778 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700779 } catch (RemoteException e) {
780 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700781 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700782 }
783
784 final PowerManager powerManager = (PowerManager) context.getSystemService(
785 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700786 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
787 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
788 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800789 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700790
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700791 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792
Wink Saville51f456f2013-04-23 14:26:51 -0700793 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900794 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700795 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700796 String[] naStrings = context.getResources().getStringArray(
797 com.android.internal.R.array.networkAttributes);
798 for (String naString : naStrings) {
799 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700800 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700801 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700802 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800803 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700804 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700805 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700806 }
Wink Saville51f456f2013-04-23 14:26:51 -0700807 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
808 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
809 n.type);
810 continue;
811 }
Wink Saville975c8482011-04-07 14:23:45 -0700812 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800813 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700814 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700815 continue;
816 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700817 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700818
Wink Saville975c8482011-04-07 14:23:45 -0700819 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700820 mNetworksDefined++;
821 } catch(Exception e) {
822 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700823 }
824 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700825
826 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
827 if (mNetConfigs[TYPE_VPN] == null) {
828 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
829 // don't need to add TYPE_VPN to mNetConfigs.
830 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
831 mNetworksDefined++; // used only in the log() statement below.
832 }
833
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900834 // Do the same for Ethernet, since it's often not specified in the configs, although many
835 // devices can use it via USB host adapters.
836 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
837 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
838 mNetworksDefined++;
839 }
840
Wink Saville5e56bc52013-07-29 15:00:57 -0700841 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700842
Robert Greenwalt50393202011-06-21 17:26:14 -0700843 mProtectedNetworks = new ArrayList<Integer>();
844 int[] protectedNetworks = context.getResources().getIntArray(
845 com.android.internal.R.array.config_protectedNetworks);
846 for (int p : protectedNetworks) {
847 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
848 mProtectedNetworks.add(p);
849 } else {
850 if (DBG) loge("Ignoring protectedNetwork " + p);
851 }
852 }
853
Erik Kline47222fc2017-04-30 19:36:15 +0900854 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800855
Luke Huang4e25ec62018-09-27 16:58:23 +0800856 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700857
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700858 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700859 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100860 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700861 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700862 intentFilter.addAction(Intent.ACTION_USER_ADDED);
863 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000864 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700865 mContext.registerReceiverAsUser(
866 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000867 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
868 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900869
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700870 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800871 mNMS.registerObserver(mTethering);
872 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700873 } catch (RemoteException e) {
874 loge("Error registering observer :" + e);
875 }
876
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 mSettingsObserver = new SettingsObserver(mContext, mHandler);
878 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800879
Chalard Jean4133a122018-06-04 13:33:12 +0900880 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
881 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400882
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400883 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900884
885 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900886 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
887 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900888
889 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
890 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
891 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
892 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
893 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
894 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
895 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900896
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900897 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900898 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900899 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900900
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900901 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
902
Luke Huang4e25ec62018-09-27 16:58:23 +0800903 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900904 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700906
Erik Kline47222fc2017-04-30 19:36:15 +0900907 private Tethering makeTethering() {
908 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900909 final TetheringDependencies deps = new TetheringDependencies() {
910 @Override
911 public boolean isTetheringSupported() {
912 return ConnectivityService.this.isTetheringSupported();
913 }
Erik Kline72302902018-06-14 17:36:40 +0900914 @Override
915 public NetworkRequest getDefaultNetworkRequest() {
916 return mDefaultRequest;
917 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900918 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800919 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900920 IoThread.get().getLooper(), new MockableSystemProperties(),
921 deps);
922 }
923
Chalard Jean26400492018-04-18 20:18:38 +0900924 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
925 final NetworkCapabilities netCap = new NetworkCapabilities();
926 netCap.addCapability(NET_CAPABILITY_INTERNET);
927 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
928 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
929 netCap.setSingleUid(uid);
930 return netCap;
931 }
932
Chalard Jeandda156a2018-01-10 21:19:32 +0900933 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900934 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900935 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900936 netCap.addCapability(NET_CAPABILITY_INTERNET);
937 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900938 if (transportType > -1) {
939 netCap.addTransportType(transportType);
940 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900941 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900942 }
943
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900944 // Used only for testing.
945 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700946 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900947 // changing ContentResolver to make registerContentObserver non-final).
948 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
949 // by subclassing SettingsObserver.
950 @VisibleForTesting
951 void updateMobileDataAlwaysOn() {
952 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
953 }
954
Erik Kline736353a2018-03-21 07:18:33 -0700955 // See FakeSettingsProvider comment above.
956 @VisibleForTesting
957 void updatePrivateDnsSettings() {
958 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
959 }
960
Erik Klineda4bfa82015-04-30 12:58:40 +0900961 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900962 final boolean enable = toBool(Settings.Global.getInt(
963 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900964 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
965 if (enable == isEnabled) {
966 return; // Nothing to do.
967 }
968
969 if (enable) {
970 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900971 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900972 } else {
973 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
974 }
975 }
976
977 private void registerSettingsCallbacks() {
978 // Watch for global HTTP proxy changes.
979 mSettingsObserver.observe(
980 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
981 EVENT_APPLY_GLOBAL_HTTP_PROXY);
982
983 // Watch for whether or not to keep mobile data always on.
984 mSettingsObserver.observe(
985 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
986 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
987 }
988
Erik Klinea24d4592018-01-11 21:07:29 +0900989 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700990 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
991 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900992 }
993 }
994
Robert Greenwalt34524f02014-05-18 16:22:10 -0700995 private synchronized int nextNetworkRequestId() {
996 return mNextNetworkRequestId++;
997 }
998
Paul Jensen67b0b072015-06-10 11:22:17 -0400999 @VisibleForTesting
1000 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001001 synchronized (mNetworkForNetId) {
1002 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1003 int netId = mNextNetId;
1004 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1005 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001006 if (!mNetIdInUse.get(netId)) {
1007 mNetIdInUse.put(netId, true);
1008 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001009 }
1010 }
1011 }
1012 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001013 }
1014
Chalard Jeanc0982912018-06-07 16:11:34 +09001015 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001016 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001017 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1018 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001020 state = nai.getNetworkState();
1021 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001023 final NetworkInfo info = new NetworkInfo(networkType, 0,
1024 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1026 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001027 final NetworkCapabilities capabilities = new NetworkCapabilities();
1028 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1029 !info.isRoaming());
1030 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001031 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001033 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001034 return state;
1035 } else {
1036 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001038 }
1039
junyulai4a192e22018-06-13 15:00:37 +08001040 @VisibleForTesting
1041 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 if (network == null) {
1043 return null;
1044 }
Erik Kline736353a2018-03-21 07:18:33 -07001045 return getNetworkAgentInfoForNetId(network.netId);
1046 }
1047
1048 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001050 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001052 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001054 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001055 synchronized (mVpns) {
1056 if (!mLockdownEnabled) {
1057 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001058 Vpn vpn = mVpns.get(user);
1059 if (vpn != null && vpn.appliesToUid(uid)) {
1060 return vpn.getUnderlyingNetworks();
1061 }
1062 }
1063 }
1064 return null;
1065 }
1066
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001067 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001068 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001069
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001070 final Network[] networks = getVpnUnderlyingNetworks(uid);
1071 if (networks != null) {
1072 // getUnderlyingNetworks() returns:
1073 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1074 // empty array => the VPN explicitly said "no default network".
1075 // non-empty array => the VPN specified one or more default networks; we use the
1076 // first one.
1077 if (networks.length > 0) {
1078 nai = getNetworkAgentInfoForNetwork(networks[0]);
1079 } else {
1080 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001081 }
1082 }
1083
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 return nai.getNetworkState();
1086 } else {
1087 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001088 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001089 }
1090
1091 /**
1092 * Check if UID should be blocked from using the network with the given LinkProperties.
1093 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001094 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1095 boolean ignoreBlocked) {
1096 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001097 if (ignoreBlocked) {
1098 return false;
1099 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001100 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001101 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1102 if (isSystem(uid)) {
1103 return false;
1104 }
Robin Lee17e61832016-05-09 13:46:28 +01001105 synchronized (mVpns) {
1106 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1107 if (vpn != null && vpn.isBlockingUid(uid)) {
1108 return true;
1109 }
1110 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001111 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001112 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 }
1114
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001115 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001116 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1117 return;
1118 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001119 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001120 synchronized (mBlockedAppUids) {
1121 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001122 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001123 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001124 blocked = false;
1125 } else {
1126 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001127 }
1128 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001129 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1130 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1131 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001132 }
1133
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001135 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1136 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001137 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001138 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1141
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 }
Hugo Benichi69744342017-11-27 10:57:16 +09001145 synchronized (mVpns) {
1146 if (mLockdownTracker != null) {
1147 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1148 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001149 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 }
1151
1152 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 * Return NetworkInfo for the active (i.e., connected) network interface.
1154 * It is assumed that at most one network is active at a time. If more
1155 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001156 * @return the info for the active network, or {@code null} if none is
1157 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 enforceAccessPermission();
1162 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1166 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168
Paul Jensen31a94f42015-02-13 14:18:39 -05001169 @Override
1170 public Network getActiveNetwork() {
1171 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001173 }
1174
1175 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001177 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001179 }
1180
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001182 final int user = UserHandle.getUserId(uid);
1183 int vpnNetId = NETID_UNSET;
1184 synchronized (mVpns) {
1185 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001186 // TODO : now that capabilities contain the UID, the appliesToUid test should
1187 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001188 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1189 }
1190 NetworkAgentInfo nai;
1191 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001192 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001193 if (nai != null) {
1194 final NetworkCapabilities requiredCaps =
1195 createDefaultNetworkCapabilitiesForUid(uid);
1196 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1197 return nai.network;
1198 }
1199 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001200 }
1201 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001202 if (nai != null
1203 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1204 nai = null;
1205 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001206 return nai != null ? nai.network : null;
1207 }
1208
Lorenzo Colitti18660282016-07-04 12:55:44 +09001209 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001210 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1211 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 final int uid = Binder.getCallingUid();
1213 NetworkState state = getUnfilteredActiveNetworkState(uid);
1214 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001215 }
1216
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001217 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001218 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001219 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001220 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001221 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001222 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001223 }
1224
1225 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 public NetworkInfo getNetworkInfo(int networkType) {
1227 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001229 if (getVpnUnderlyingNetworks(uid) != null) {
1230 // A VPN is active, so we may need to return one of its underlying networks. This
1231 // information is not available in LegacyTypeTracker, so we have to get it from
1232 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001233 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001234 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001235 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001237 }
1238 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001239 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
1242
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001244 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001246 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001247 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001248 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001249 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001250 return state.networkInfo;
1251 } else {
1252 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001253 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001254 }
1255
1256 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 public NetworkInfo[] getAllNetworkInfo() {
1258 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001259 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001260 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1261 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 NetworkInfo info = getNetworkInfo(networkType);
1263 if (info != null) {
1264 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001267 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
1269
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001270 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001271 public Network getNetworkForType(int networkType) {
1272 enforceAccessPermission();
1273 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001274 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001275 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001276 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001277 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001278 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001279 }
1280
1281 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 public Network[] getAllNetworks() {
1283 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001284 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001285 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001287 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001288 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001289 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001290 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001291 }
1292
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001293 @Override
1294 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1295 // The basic principle is: if an app's traffic could possibly go over a
1296 // network, without the app doing anything multinetwork-specific,
1297 // (hence, by "default"), then include that network's capabilities in
1298 // the array.
1299 //
1300 // In the normal case, app traffic only goes over the system's default
1301 // network connection, so that's the only network returned.
1302 //
1303 // With a VPN in force, some app traffic may go into the VPN, and thus
1304 // over whatever underlying networks the VPN specifies, while other app
1305 // traffic may go over the system default network (e.g.: a split-tunnel
1306 // VPN, or an app disallowed by the VPN), so the set of networks
1307 // returned includes the VPN's underlying networks and the system
1308 // default.
1309 enforceAccessPermission();
1310
Chalard Jean4133a122018-06-04 13:33:12 +09001311 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001312
1313 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001314 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001315 if (nc != null) {
1316 result.put(nai.network, nc);
1317 }
1318
Hugo Benichi69744342017-11-27 10:57:16 +09001319 synchronized (mVpns) {
1320 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001321 Vpn vpn = mVpns.get(userId);
1322 if (vpn != null) {
1323 Network[] networks = vpn.getUnderlyingNetworks();
1324 if (networks != null) {
1325 for (Network network : networks) {
1326 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001327 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001328 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001329 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001330 }
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1338 out = result.values().toArray(out);
1339 return out;
1340 }
1341
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001342 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001343 public boolean isNetworkSupported(int networkType) {
1344 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001345 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001346 }
1347
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001348 /**
1349 * Return LinkProperties for the active (i.e., connected) default
1350 * network interface. It is assumed that at most one default network
1351 * is active at a time. If more than one is active, it is indeterminate
1352 * which will be returned.
1353 * @return the ip properties for the active network, or {@code null} if
1354 * none is active
1355 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001357 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001358 enforceAccessPermission();
1359 final int uid = Binder.getCallingUid();
1360 NetworkState state = getUnfilteredActiveNetworkState(uid);
1361 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 }
1363
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001365 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001366 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1368 if (nai != null) {
1369 synchronized (nai) {
1370 return new LinkProperties(nai.linkProperties);
1371 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001372 }
1373 return null;
1374 }
1375
Robert Greenwalt12e67352014-05-13 21:41:06 -07001376 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001377 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001378 public LinkProperties getLinkProperties(Network network) {
1379 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001380 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1381 }
1382
1383 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1384 if (nai == null) {
1385 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001386 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001387 synchronized (nai) {
1388 return new LinkProperties(nai.linkProperties);
1389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001390 }
1391
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001392 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001393 if (nai != null) {
1394 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001395 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001396 return networkCapabilitiesRestrictedForCallerPermissions(
1397 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001398 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001399 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001400 }
1401 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001402 return null;
1403 }
1404
1405 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001406 public NetworkCapabilities getNetworkCapabilities(Network network) {
1407 enforceAccessPermission();
1408 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1409 }
1410
Chalard Jeanb03a6222018-04-11 21:09:10 +09001411 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001412 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001413 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001414 if (!checkSettingsPermission(callerPid, callerUid)) {
1415 newNc.setUids(null);
1416 newNc.setSSID(null);
1417 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001418 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001419 }
1420
Chalard Jeanb552c462018-02-21 18:43:54 +09001421 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1422 if (!checkSettingsPermission()) {
1423 nc.setSingleUid(Binder.getCallingUid());
1424 }
1425 }
1426
Chalard Jean26aa91a2018-03-20 19:13:57 +09001427 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1428 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1429 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1430 }
1431 }
1432
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001433 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001434 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001435 // Require internal since we're handing out IMSI details
1436 enforceConnectivityInternalPermission();
1437
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001438 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 for (Network network : getAllNetworks()) {
1440 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1441 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001442 // TODO (b/73321673) : NetworkState contains a copy of the
1443 // NetworkCapabilities, which may contain UIDs of apps to which the
1444 // network applies. Should the UIDs be cleared so as not to leak or
1445 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001446 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001447 }
1448 }
1449 return result.toArray(new NetworkState[result.size()]);
1450 }
1451
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001452 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001453 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001454 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001455 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1456 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1457 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001458 }
1459
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001460 @Override
1461 public boolean isActiveNetworkMetered() {
1462 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001463
Eric Enslenc81ef192018-02-07 18:03:53 -08001464 final int uid = Binder.getCallingUid();
1465 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001466 if (caps != null) {
1467 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1468 } else {
1469 // Always return the most conservative value
1470 return true;
1471 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001472 }
1473
Jeff Sharkey216c1812012-08-05 14:29:23 -07001474 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1475 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001476 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001477 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001478 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001479 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001480 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001481
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001482 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 * Ensure that a network route exists to deliver traffic to the specified
1484 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001485 * @param networkType the type of the network over which traffic to the
1486 * specified host is to be routed
1487 * @param hostAddress the IP address of the host to which the route is
1488 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 * @return {@code true} on success, {@code false} on failure
1490 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001491 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001492 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001494 if (mProtectedNetworks.contains(networkType)) {
1495 enforceConnectivityInternalPermission();
1496 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001497
Chad Brubakerc0234532014-02-14 13:24:29 -08001498 InetAddress addr;
1499 try {
1500 addr = InetAddress.getByAddress(hostAddress);
1501 } catch (UnknownHostException e) {
1502 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1503 return false;
1504 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001507 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 return false;
1509 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001510
1511 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1512 if (nai == null) {
1513 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1514 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1515 } else {
1516 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1517 }
1518 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001519 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001520
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001521 DetailedState netState;
1522 synchronized (nai) {
1523 netState = nai.networkInfo.getDetailedState();
1524 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001525
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001526 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001527 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001528 log("requestRouteToHostAddress on down network "
1529 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001530 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001531 }
1532 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001534
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001535 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001536 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001537 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001538 LinkProperties lp;
1539 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001540 synchronized (nai) {
1541 lp = nai.linkProperties;
1542 netId = nai.network.netId;
1543 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001544 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001545 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1546 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001547 } finally {
1548 Binder.restoreCallingIdentity(token);
1549 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001550 }
1551
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001552 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001553 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001554 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001555 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001556 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001557 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001558 if (bestRoute.getGateway().equals(addr)) {
1559 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001560 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001561 } else {
1562 // if we will connect to this through another route, add a direct route
1563 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001564 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001565 }
1566 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001567 if (DBG) log("Adding legacy route " + bestRoute +
1568 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001569 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001570 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001571 } catch (Exception e) {
1572 // never crash - catch them all
1573 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001574 return false;
1575 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001576 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578
dalyk7301aa42018-03-05 12:42:22 -05001579 @VisibleForTesting
1580 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1581 @Override
1582 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1583 String hostname, boolean validated) {
1584 try {
1585 mHandler.sendMessage(mHandler.obtainMessage(
1586 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1587 new PrivateDnsValidationUpdate(netId,
1588 InetAddress.parseNumericAddress(ipAddress),
1589 hostname, validated)));
1590 } catch (IllegalArgumentException e) {
1591 loge("Error parsing ip address in validation event");
1592 }
1593 }
1594 };
1595
1596 @VisibleForTesting
1597 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001598 final IIpConnectivityMetrics ipConnectivityMetrics =
1599 IIpConnectivityMetrics.Stub.asInterface(
1600 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1601 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001602 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001603 return;
dalyk7301aa42018-03-05 12:42:22 -05001604 }
1605
1606 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001607 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001608 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1609 mNetdEventCallback);
1610 } catch (Exception e) {
1611 loge("Error registering netd callback: " + e);
1612 }
1613 }
1614
Jeff Sharkey75d31892018-01-18 22:01:59 +09001615 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001616 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001617 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001618 // TODO: notify UID when it has requested targeted updates
1619 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001620 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001621 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001622 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001623 if (restrictBackground) {
1624 log("onRestrictBackgroundChanged(true): disabling tethering");
1625 mTethering.untetherAll();
1626 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001627 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001628 };
1629
Robin Lee3b3dd942015-05-12 18:14:58 +01001630 /**
1631 * Require that the caller is either in the same user or has appropriate permission to interact
1632 * across users.
1633 *
1634 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1635 */
1636 private void enforceCrossUserPermission(int userId) {
1637 if (userId == UserHandle.getCallingUserId()) {
1638 // Not a cross-user call.
1639 return;
1640 }
1641 mContext.enforceCallingOrSelfPermission(
1642 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1643 "ConnectivityService");
1644 }
1645
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001646 private void enforceInternetPermission() {
1647 mContext.enforceCallingOrSelfPermission(
1648 android.Manifest.permission.INTERNET,
1649 "ConnectivityService");
1650 }
1651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001653 mContext.enforceCallingOrSelfPermission(
1654 android.Manifest.permission.ACCESS_NETWORK_STATE,
1655 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
1658 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001659 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661
Charles He36738632017-05-15 17:07:18 +01001662 private void enforceSettingsPermission() {
1663 mContext.enforceCallingOrSelfPermission(
1664 android.Manifest.permission.NETWORK_SETTINGS,
1665 "ConnectivityService");
1666 }
1667
Chalard Jeanb552c462018-02-21 18:43:54 +09001668 private boolean checkSettingsPermission() {
1669 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1670 android.Manifest.permission.NETWORK_SETTINGS);
1671 }
1672
1673 private boolean checkSettingsPermission(int pid, int uid) {
1674 return PERMISSION_GRANTED == mContext.checkPermission(
1675 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1676 }
1677
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001678 private void enforceTetherAccessPermission() {
1679 mContext.enforceCallingOrSelfPermission(
1680 android.Manifest.permission.ACCESS_NETWORK_STATE,
1681 "ConnectivityService");
1682 }
1683
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001684 private void enforceConnectivityInternalPermission() {
1685 mContext.enforceCallingOrSelfPermission(
1686 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1687 "ConnectivityService");
1688 }
1689
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001690 private boolean checkNetworkStackPermission() {
1691 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1692 android.Manifest.permission.NETWORK_STACK);
1693 }
1694
Hugo Benichi514da602016-07-19 15:59:27 +09001695 private void enforceConnectivityRestrictedNetworksPermission() {
1696 try {
1697 mContext.enforceCallingOrSelfPermission(
1698 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1699 "ConnectivityService");
1700 return;
1701 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1702 enforceConnectivityInternalPermission();
1703 }
1704
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001705 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001706 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001707 }
1708
Lorenzo Colitti18660282016-07-04 12:55:44 +09001709 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001710 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001711 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001712 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001713 }
1714
1715 private void sendInetConditionBroadcast(NetworkInfo info) {
1716 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1717 }
1718
Wink Saville628b0852011-08-04 15:01:58 -07001719 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001720 synchronized (mVpns) {
1721 if (mLockdownTracker != null) {
1722 info = new NetworkInfo(info);
1723 mLockdownTracker.augmentNetworkInfo(info);
1724 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001725 }
1726
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001727 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001728 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001729 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (info.isFailover()) {
1731 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1732 info.setFailover(false);
1733 }
1734 if (info.getReason() != null) {
1735 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1736 }
1737 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001738 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1739 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001741 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001742 return intent;
1743 }
1744
1745 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1746 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1747 }
1748
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001749 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001750 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1751 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1752 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001753 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001754 final long ident = Binder.clearCallingIdentity();
1755 try {
1756 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1757 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1758 } finally {
1759 Binder.restoreCallingIdentity(ident);
1760 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001761 }
1762
Mike Lockwood0f79b542009-08-14 14:18:49 -04001763 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001764 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001765 if (!mSystemReady) {
1766 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001767 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001768 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001769 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001770 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001771 }
1772
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001773 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001774 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001775 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001776 final NetworkInfo ni = intent.getParcelableExtra(
1777 ConnectivityManager.EXTRA_NETWORK_INFO);
1778 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1779 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1780 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001781 } else {
1782 BroadcastOptions opts = BroadcastOptions.makeBasic();
1783 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1784 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001785 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001786 final IBatteryStats bs = BatteryStatsService.getService();
1787 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001788 bs.noteConnectivityChanged(intent.getIntExtra(
1789 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001790 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001791 } catch (RemoteException e) {
1792 }
Chad Brubakerac925012018-03-08 10:37:09 -08001793 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001794 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001795 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001796 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001797 } finally {
1798 Binder.restoreCallingIdentity(ident);
1799 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001800 }
1801 }
1802
1803 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001804 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001805 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001806
Hugo Benichi20035e02017-04-26 14:53:28 +09001807 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001808 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001809 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001810 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001811 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001812 }
1813 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001814 // load the global proxy at startup
1815 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001816
Robin Lee244ce8e2016-01-05 18:03:46 +00001817 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1818 // for user to unlock device too.
1819 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001820
Erik Klineda4bfa82015-04-30 12:58:40 +09001821 // Configure whether mobile data is always on.
1822 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1823
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001825
1826 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001830 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001831 *
1832 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001833 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001834 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1836 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001837
1838 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001839 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001840
Robert Greenwalt7b816022014-04-18 15:25:25 -07001841 if (networkAgent.networkCapabilities.hasTransport(
1842 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001843 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1844 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001845 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001846 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001847 } else if (networkAgent.networkCapabilities.hasTransport(
1848 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001849 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1850 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001851 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001852 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001853 } else {
1854 // do not track any other networks
1855 timeout = 0;
1856 }
1857
Robert Greenwalt7b816022014-04-18 15:25:25 -07001858 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001859 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001860 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001861 } catch (Exception e) {
1862 // You shall not crash!
1863 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001864 }
1865 }
1866 }
1867
1868 /**
1869 * Remove data activity tracking when network disconnects.
1870 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001871 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1872 final String iface = networkAgent.linkProperties.getInterfaceName();
1873 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001874
Robert Greenwalt7b816022014-04-18 15:25:25 -07001875 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1876 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001877 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001878 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08001879 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001880 } catch (Exception e) {
1881 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001882 }
1883 }
1884 }
1885
1886 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08001887 * Update data activity tracking when network state is updated.
1888 */
1889 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
1890 NetworkAgentInfo oldNetwork) {
1891 if (newNetwork != null) {
1892 setupDataActivityTracking(newNetwork);
1893 }
1894 if (oldNetwork != null) {
1895 removeDataActivityTracking(oldNetwork);
1896 }
1897 }
1898 /**
Chalard Jean4d660112018-06-04 16:52:49 +09001899 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09001900 * and set it on it's iface.
1901 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001902 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1903 final String iface = newLp.getInterfaceName();
1904 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001905 if (oldLp == null && mtu == 0) {
1906 // Silently ignore unset MTU value.
1907 return;
1908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001909 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1910 if (VDBG) log("identical MTU - not setting");
1911 return;
1912 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001913 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001914 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001915 return;
1916 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001917
w1997615afd812014-08-05 15:18:11 -07001918 // Cannot set MTU without interface name
1919 if (TextUtils.isEmpty(iface)) {
1920 loge("Setting MTU size with null iface.");
1921 return;
1922 }
1923
Robert Greenwalt7b816022014-04-18 15:25:25 -07001924 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001925 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08001926 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001927 } catch (Exception e) {
1928 Slog.e(TAG, "exception in setMtu()" + e);
1929 }
1930 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001931
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001932 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001933 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1934
1935 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001936 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001937 protected MockableSystemProperties getSystemProperties() {
1938 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001939 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001940
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001941 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1942 if (isDefaultNetwork(nai) == false) {
1943 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001944 }
1945
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001946 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1947 String[] values = null;
1948 if (tcpBufferSizes != null) {
1949 values = tcpBufferSizes.split(",");
1950 }
1951
1952 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001953 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001954 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1955 values = tcpBufferSizes.split(",");
1956 }
1957
1958 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1959
1960 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001961 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001962
1963 final String prefix = "/sys/kernel/ipv4/tcp_";
1964 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1965 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1966 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1967 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1968 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1969 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1970 mCurrentTcpBufferSizes = tcpBufferSizes;
1971 } catch (IOException e) {
1972 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001973 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001974
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001975 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001976 Settings.Global.TCP_DEFAULT_INIT_RWND,
1977 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001978 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1979 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001980 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001981 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001982 }
1983
Robert Greenwalt562cc542014-05-15 18:07:26 -07001984 @Override
1985 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001986 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001987 NETWORK_RESTORE_DELAY_PROP_NAME);
1988 if(restoreDefaultNetworkDelayStr != null &&
1989 restoreDefaultNetworkDelayStr.length() != 0) {
1990 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001991 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001992 } catch (NumberFormatException e) {
1993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001995 // if the system property isn't set, use the value for the apn type
1996 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1997
1998 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1999 (mNetConfigs[networkType] != null)) {
2000 ret = mNetConfigs[networkType].restoreTime;
2001 }
2002 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002005 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2006 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2007 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002008 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002009 // Start gathering diagnostic information.
2010 netDiags.add(new NetworkDiagnostics(
2011 nai.network,
2012 new LinkProperties(nai.linkProperties), // Must be a copy.
2013 DIAG_TIME_MS));
2014 }
2015
2016 for (NetworkDiagnostics netDiag : netDiags) {
2017 pw.println();
2018 netDiag.waitForMeasurements();
2019 netDiag.dump(pw);
2020 }
2021 }
2022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002024 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002025 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2026 }
2027
2028 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002029 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002030 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002031 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002032
Erik Kline3f8306b2018-05-01 16:51:44 +09002033 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002034 dumpNetworkDiagnostics(pw);
2035 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002036 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002037 mTethering.dump(fd, pw, args);
2038 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002039 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2040 dumpNetworks(pw);
2041 return;
2042 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2043 dumpNetworkRequests(pw);
2044 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002045 }
Erik Kline379747a2015-06-05 17:47:34 +09002046
Lorenzo Colittie3805462015-06-03 11:18:24 +09002047 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002048 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002049 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002050 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002051 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002052 pw.println();
2053
Paul Jensen85cf78e2015-06-25 13:25:07 -04002054 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002055 pw.print("Active default network: ");
2056 if (defaultNai == null) {
2057 pw.println("none");
2058 } else {
2059 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002061 pw.println();
2062
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002063 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002064 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002065 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002066 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002067 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002068
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002069 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002070 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002071 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002072 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002073 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002074
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002075 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002076
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002077 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002078 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002079
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002080 pw.println();
2081 mKeepaliveTracker.dump(pw);
2082
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002083 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002084 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002085
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002086 pw.println();
2087 mMultipathPolicyTracker.dump(pw);
2088
Erik Kline3f8306b2018-05-01 16:51:44 +09002089 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002090 pw.println();
2091 synchronized (mValidationLogs) {
2092 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002093 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002094 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002095 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002096 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002097 pw.decreaseIndent();
2098 }
2099 }
Erik Kline7523eb32015-07-09 18:24:03 +09002100
2101 pw.println();
2102 pw.println("mNetworkRequestInfoLogs (most recent first):");
2103 pw.increaseIndent();
2104 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2105 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002106
2107 pw.println();
2108 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2109 pw.increaseIndent();
2110 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2111 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002112
2113 pw.println();
2114 pw.println("NetTransition WakeLock activity (most recent first):");
2115 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002116 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2117 pw.println("total releases: " + mTotalWakelockReleases);
2118 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2119 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2120 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2121 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2122 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2123 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002124 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002125
2126 pw.println();
2127 pw.println("bandwidth update requests (by uid):");
2128 pw.increaseIndent();
2129 synchronized (mBandwidthRequests) {
2130 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2131 pw.println("[" + mBandwidthRequests.keyAt(i)
2132 + "]: " + mBandwidthRequests.valueAt(i));
2133 }
2134 }
2135 pw.decreaseIndent();
2136
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002137 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
2140
Hugo Benichi14683812018-09-03 08:32:56 +09002141 private void dumpNetworks(IndentingPrintWriter pw) {
2142 for (NetworkAgentInfo nai : networksSortedById()) {
2143 pw.println(nai.toString());
2144 pw.increaseIndent();
2145 pw.println(String.format(
2146 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2147 nai.numForegroundNetworkRequests(),
2148 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2149 nai.numBackgroundNetworkRequests(),
2150 nai.numNetworkRequests()));
2151 pw.increaseIndent();
2152 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2153 pw.println(nai.requestAt(i).toString());
2154 }
2155 pw.decreaseIndent();
2156 pw.println("Lingered:");
2157 pw.increaseIndent();
2158 nai.dumpLingerTimers(pw);
2159 pw.decreaseIndent();
2160 pw.decreaseIndent();
2161 }
2162 }
2163
2164 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2165 for (NetworkRequestInfo nri : requestsSortedById()) {
2166 pw.println(nri.toString());
2167 }
2168 }
2169
Hugo Benichia2a917c2018-09-03 08:19:02 +09002170 /**
2171 * Return an array of all current NetworkAgentInfos sorted by network id.
2172 */
2173 private NetworkAgentInfo[] networksSortedById() {
2174 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2175 networks = mNetworkAgentInfos.values().toArray(networks);
2176 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2177 return networks;
2178 }
2179
2180 /**
2181 * Return an array of all current NetworkRequest sorted by request id.
2182 */
2183 private NetworkRequestInfo[] requestsSortedById() {
2184 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2185 requests = mNetworkRequests.values().toArray(requests);
2186 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2187 return requests;
2188 }
2189
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002190 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002191 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002192 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002193 if (officialNai != null && officialNai.equals(nai)) return true;
2194 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002195 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002196 " - " + nai);
2197 }
2198 return false;
2199 }
2200
Robert Greenwalt42acef32009-08-12 16:08:25 -07002201 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002202 private class NetworkStateTrackerHandler extends Handler {
2203 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002204 super(looper);
2205 }
2206
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002207 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002209 default:
2210 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002211 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 handleAsyncChannelHalfConnect(msg);
2213 break;
2214 }
2215 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2216 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2217 if (nai != null) nai.asyncChannel.disconnect();
2218 break;
2219 }
2220 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2221 handleAsyncChannelDisconnected(msg);
2222 break;
2223 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002224 }
2225 return true;
2226 }
2227
2228 private void maybeHandleNetworkAgentMessage(Message msg) {
2229 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2230 if (nai == null) {
2231 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002232 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002233 }
2234 return;
2235 }
2236
2237 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002239 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2240 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002241 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2242 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002243 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002244 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002245 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002246 break;
2247 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002249 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002250 break;
2251 }
2252 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002253 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002254 updateNetworkInfo(nai, info);
2255 break;
2256 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002257 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002258 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002259 break;
2260 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002261 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002262 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2263 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002264 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002265 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002266 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002267 break;
2268 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002269 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002270 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2271 break;
2272 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002273 }
2274 }
2275
2276 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2277 switch (msg.what) {
2278 default:
2279 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002280 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002281 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002282 if (nai == null) break;
2283
2284 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2285 final boolean wasValidated = nai.lastValidated;
2286 final boolean wasDefault = isDefaultNetwork(nai);
2287
Erik Klinea24d4592018-01-11 21:07:29 +09002288 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2289
Erik Klinea24d4592018-01-11 21:07:29 +09002290 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002291 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2292 ? " with redirect to " + redirectUrl
2293 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002294 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2295 }
Erik Klinea24d4592018-01-11 21:07:29 +09002296 if (valid != nai.lastValidated) {
2297 if (wasDefault) {
2298 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2299 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002300 }
Erik Klinea24d4592018-01-11 21:07:29 +09002301 final int oldScore = nai.getCurrentScore();
2302 nai.lastValidated = valid;
2303 nai.everValidated |= valid;
2304 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2305 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2306 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002307 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002308 }
2309 updateInetCondition(nai);
2310 // Let the NetworkAgent know the state of its network
2311 Bundle redirectUrlBundle = new Bundle();
2312 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2313 nai.asyncChannel.sendMessage(
2314 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2315 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2316 0, redirectUrlBundle);
2317 if (wasValidated && !nai.lastValidated) {
2318 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002319 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002320 break;
2321 }
Paul Jensen869868be2014-05-15 10:33:05 -04002322 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002323 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002324 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002325 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002326 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002327 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002328 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002329 nai.lastCaptivePortalDetected = visible;
2330 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002331 if (nai.lastCaptivePortalDetected &&
2332 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2333 if (DBG) log("Avoiding captive portal network: " + nai.name());
2334 nai.asyncChannel.sendMessage(
2335 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2336 teardownUnneededNetwork(nai);
2337 break;
2338 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002339 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002340 }
2341 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002342 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002343 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002344 if (nai == null) {
2345 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2346 break;
2347 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002348 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002349 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002350 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002351 }
Paul Jensen869868be2014-05-15 10:33:05 -04002352 }
Paul Jensen869868be2014-05-15 10:33:05 -04002353 break;
2354 }
Erik Klinea24d4592018-01-11 21:07:29 +09002355 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002356 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002357 if (nai == null) break;
2358
Erik Kline736353a2018-03-21 07:18:33 -07002359 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002360 break;
2361 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002362 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002363 return true;
2364 }
2365
Calvin Onbe96da12016-10-11 15:10:46 -07002366 private int getCaptivePortalMode() {
2367 return Settings.Global.getInt(mContext.getContentResolver(),
2368 Settings.Global.CAPTIVE_PORTAL_MODE,
2369 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2370 }
2371
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002372 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2373 switch (msg.what) {
2374 default:
2375 return false;
2376 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2377 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2378 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2379 handleLingerComplete(nai);
2380 }
2381 break;
2382 }
2383 }
2384 return true;
2385 }
2386
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002387 @Override
2388 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002389 if (!maybeHandleAsyncChannelMessage(msg) &&
2390 !maybeHandleNetworkMonitorMessage(msg) &&
2391 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002392 maybeHandleNetworkAgentMessage(msg);
2393 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002394 }
2395 }
2396
Erik Kline736353a2018-03-21 07:18:33 -07002397 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2398 return NetworkMonitor.isValidationRequired(
2399 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2400 }
2401
Erik Klinec6d00222018-06-26 18:53:43 +09002402 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2403 if (nai == null) return;
2404 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2405 // in order to restart a validation pass from within netd.
2406 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2407 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2408 updateDnses(nai.linkProperties, null, nai.network.netId);
2409 }
2410 }
2411
Erik Klinea24d4592018-01-11 21:07:29 +09002412 private void handlePrivateDnsSettingsChanged() {
2413 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2414
2415 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002416 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002417 if (networkRequiresValidation(nai)) {
2418 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2419 }
Erik Klinea24d4592018-01-11 21:07:29 +09002420 }
2421 }
2422
Erik Kline736353a2018-03-21 07:18:33 -07002423 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2424 // Private DNS only ever applies to networks that might provide
2425 // Internet access and therefore also require validation.
2426 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002427
Erik Kline736353a2018-03-21 07:18:33 -07002428 // Notify the NetworkMonitor thread in case it needs to cancel or
2429 // schedule DNS resolutions. If a DNS resolution is required the
2430 // result will be sent back to us.
2431 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2432
2433 // With Private DNS bypass support, we can proceed to update the
2434 // Private DNS config immediately, even if we're in strict mode
2435 // and have not yet resolved the provider name into a set of IPs.
2436 updatePrivateDns(nai, cfg);
2437 }
2438
2439 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2440 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002441 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002442 }
2443
dalyk7301aa42018-03-05 12:42:22 -05002444 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2445 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2446 if (nai == null) {
2447 return;
2448 }
2449 mDnsManager.updatePrivateDnsValidation(update);
2450 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2451 }
2452
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002453 private void updateLingerState(NetworkAgentInfo nai, long now) {
2454 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2455 // 2. If the network was lingering and there are now requests, unlinger it.
2456 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2457 // one lingered request, start lingering.
2458 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002459 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002460 if (DBG) log("Unlingering " + nai.name());
2461 nai.unlinger();
2462 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002463 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002464 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002465 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002466 nai.linger();
2467 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2468 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2469 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002470 }
2471
Robert Greenwalt7b816022014-04-18 15:25:25 -07002472 private void handleAsyncChannelHalfConnect(Message msg) {
2473 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002474 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002475 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2476 if (VDBG) log("NetworkFactory connected");
2477 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002478 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002479 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002480 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002481 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002482 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002483 }
2484 } else {
2485 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002486 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002487 }
2488 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2489 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2490 if (VDBG) log("NetworkAgent connected");
2491 // A network agent has requested a connection. Establish the connection.
2492 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2493 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2494 } else {
2495 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002496 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002497 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002498 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002499 synchronized (mNetworkForNetId) {
2500 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002501 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002502 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002503 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002504 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002505 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002506 }
2507 }
2508 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002509
Chalard Jean392971c2018-05-11 20:19:20 +09002510 // This is a no-op if it's called with a message designating a network that has
2511 // already been destroyed, because its reference will not be found in the relevant
2512 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002513 private void handleAsyncChannelDisconnected(Message msg) {
2514 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2515 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002516 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002517 } else {
2518 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2519 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002520 }
2521 }
2522
Chalard Jean392971c2018-05-11 20:19:20 +09002523 // Destroys a network, remove references to it from the internal state managed by
2524 // ConnectivityService, free its interfaces and clean up.
2525 // Must be called on the Handler thread.
2526 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2527 if (DBG) {
2528 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2529 }
2530 // A network agent has disconnected.
2531 // TODO - if we move the logic to the network agent (have them disconnect
2532 // because they lost all their requests or because their score isn't good)
2533 // then they would disconnect organically, report their new state and then
2534 // disconnect the channel.
2535 if (nai.networkInfo.isConnected()) {
2536 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2537 null, null);
2538 }
2539 final boolean wasDefault = isDefaultNetwork(nai);
2540 if (wasDefault) {
2541 mDefaultInetConditionPublished = 0;
2542 // Log default network disconnection before required book-keeping.
2543 // Let rematchAllNetworksAndRequests() below record a new default network event
2544 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2545 // whose timestamps tell how long it takes to recover a default network.
2546 long now = SystemClock.elapsedRealtime();
2547 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2548 }
2549 notifyIfacesChangedForNetworkStats();
2550 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2551 // by other networks that are already connected. Perhaps that can be done by
2552 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2553 // of rematchAllNetworksAndRequests
2554 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2555 mKeepaliveTracker.handleStopAllKeepalives(nai,
2556 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2557 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2558 // Disable wakeup packet monitoring for each interface.
2559 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2560 }
2561 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2562 mNetworkAgentInfos.remove(nai.messenger);
2563 nai.maybeStopClat();
2564 synchronized (mNetworkForNetId) {
2565 // Remove the NetworkAgent, but don't mark the netId as
2566 // available until we've told netd to delete it below.
2567 mNetworkForNetId.remove(nai.network.netId);
2568 }
2569 // Remove all previously satisfied requests.
2570 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2571 NetworkRequest request = nai.requestAt(i);
2572 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2573 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2574 clearNetworkForRequest(request.requestId);
2575 sendUpdatedScoreToFactories(request, 0);
2576 }
2577 }
2578 nai.clearLingerState();
2579 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002580 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002581 notifyLockdownVpn(nai);
2582 ensureNetworkTransitionWakelock(nai.name());
2583 }
2584 mLegacyTypeTracker.remove(nai, wasDefault);
2585 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2586 updateAllVpnsCapabilities();
2587 }
2588 rematchAllNetworksAndRequests(null, 0);
2589 mLingerMonitor.noteDisconnect(nai);
2590 if (nai.created) {
2591 // Tell netd to clean up the configuration for this network
2592 // (routing rules, DNS, etc).
2593 // This may be slow as it requires a lot of netd shelling out to ip and
2594 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2595 // after we've rematched networks with requests which should make a potential
2596 // fallback network the default or requested a new network from the
2597 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2598 // long time.
2599 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002600 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002601 } catch (Exception e) {
2602 loge("Exception removing network: " + e);
2603 }
2604 mDnsManager.removeNetwork(nai.network);
2605 }
2606 synchronized (mNetworkForNetId) {
2607 mNetIdInUse.delete(nai.network.netId);
2608 }
2609 }
2610
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002611 // If this method proves to be too slow then we can maintain a separate
2612 // pendingIntent => NetworkRequestInfo map.
2613 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2614 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2615 Intent intent = pendingIntent.getIntent();
2616 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2617 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2618 if (existingPendingIntent != null &&
2619 existingPendingIntent.getIntent().filterEquals(intent)) {
2620 return entry.getValue();
2621 }
2622 }
2623 return null;
2624 }
2625
2626 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2627 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2628
2629 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2630 if (existingRequest != null) { // remove the existing request.
2631 if (DBG) log("Replacing " + existingRequest.request + " with "
2632 + nri.request + " because their intents matched.");
2633 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2634 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002635 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002636 }
2637
Erik Klineda4bfa82015-04-30 12:58:40 +09002638 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002639 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002640 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002641 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002642 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002643 if (nri.request.networkCapabilities.hasSignalStrength() &&
2644 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2645 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002646 }
2647 }
2648 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002649 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002650 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002651 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002652 }
2653 }
2654
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002655 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2656 int callingUid) {
2657 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2658 if (nri != null) {
2659 handleReleaseNetworkRequest(nri.request, callingUid);
2660 }
2661 }
2662
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002663 // Determines whether the network is the best (or could become the best, if it validated), for
2664 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2665 // on the value of reason:
2666 //
2667 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2668 // then it should be torn down.
2669 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2670 // then it should be lingered.
2671 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2672 final int numRequests;
2673 switch (reason) {
2674 case TEARDOWN:
2675 numRequests = nai.numRequestNetworkRequests();
2676 break;
2677 case LINGER:
2678 numRequests = nai.numForegroundNetworkRequests();
2679 break;
2680 default:
2681 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2682 return true;
2683 }
2684
2685 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002686 return false;
2687 }
Paul Jensene0988542015-06-25 15:30:08 -04002688 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002689 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2690 // Background requests don't affect lingering.
2691 continue;
2692 }
2693
Paul Jensene0988542015-06-25 15:30:08 -04002694 // If this Network is already the highest scoring Network for a request, or if
2695 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002696 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002697 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002698 // Note that this catches two important cases:
2699 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2700 // is currently satisfying the request. This is desirable when
2701 // cellular ends up validating but WiFi does not.
2702 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002703 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002704 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002705 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002706 nai.getCurrentScoreAsValidated())) {
2707 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002708 }
2709 }
Paul Jensene0988542015-06-25 15:30:08 -04002710 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002711 }
2712
Erik Klineacdd6392016-07-07 16:50:58 +09002713 private NetworkRequestInfo getNriForAppRequest(
2714 NetworkRequest request, int callingUid, String requestedOperation) {
2715 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2716
Robert Greenwalt9258c642014-03-26 16:47:06 -07002717 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002718 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002719 log(String.format("UID %d attempted to %s for unowned request %s",
2720 callingUid, requestedOperation, nri));
2721 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002722 }
Erik Klineacdd6392016-07-07 16:50:58 +09002723 }
2724
2725 return nri;
2726 }
2727
Erik Kline57faba92015-11-25 12:49:38 +09002728 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002729 if (mNetworkRequests.get(nri.request) == null) {
2730 return;
Erik Kline57faba92015-11-25 12:49:38 +09002731 }
Hugo Benichicd952782017-09-20 11:20:14 +09002732 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002733 return;
2734 }
2735 if (VDBG || (DBG && nri.request.isRequest())) {
2736 log("releasing " + nri.request + " (timeout)");
2737 }
2738 handleRemoveNetworkRequest(nri);
2739 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002740 }
2741
Erik Klineacdd6392016-07-07 16:50:58 +09002742 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002743 final NetworkRequestInfo nri =
2744 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2745 if (nri == null) {
2746 return;
Erik Kline57faba92015-11-25 12:49:38 +09002747 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002748 if (VDBG || (DBG && nri.request.isRequest())) {
2749 log("releasing " + nri.request + " (release request)");
2750 }
2751 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002752 }
Erik Klineacdd6392016-07-07 16:50:58 +09002753
Hugo Benichidba33db2017-03-23 22:40:44 +09002754 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002755 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002756 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002757
Erik Klineacdd6392016-07-07 16:50:58 +09002758 synchronized (mUidToNetworkRequestCount) {
2759 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2760 if (requests < 1) {
2761 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2762 nri.mUid);
2763 } else if (requests == 1) {
2764 mUidToNetworkRequestCount.removeAt(
2765 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2766 } else {
2767 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2768 }
2769 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002770
Erik Klineacdd6392016-07-07 16:50:58 +09002771 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2772 if (nri.request.isRequest()) {
2773 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002774 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002775 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002776 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002777 nai.removeRequest(nri.request.requestId);
2778 if (VDBG) {
2779 log(" Removing from current network " + nai.name() +
2780 ", leaving " + nai.numNetworkRequests() + " requests.");
2781 }
2782 // If there are still lingered requests on this network, don't tear it down,
2783 // but resume lingering instead.
2784 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002785 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002786 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2787 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002788 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002789 wasKept = true;
2790 }
Hugo Benichicd952782017-09-20 11:20:14 +09002791 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002792 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2793 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002794 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002795 }
Erik Klineacdd6392016-07-07 16:50:58 +09002796 }
2797
2798 // TODO: remove this code once we know that the Slog.wtf is never hit.
2799 //
2800 // Find all networks that are satisfying this request and remove the request
2801 // from their request lists.
2802 // TODO - it's my understanding that for a request there is only a single
2803 // network satisfying it, so this loop is wasteful
2804 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2805 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2806 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2807 otherNai.name() + ", but mNetworkAgentInfos says " +
2808 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002809 }
2810 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002811
Erik Klineacdd6392016-07-07 16:50:58 +09002812 // Maintain the illusion. When this request arrived, we might have pretended
2813 // that a network connected to serve it, even though the network was already
2814 // connected. Now that this request has gone away, we might have to pretend
2815 // that the network disconnected. LegacyTypeTracker will generate that
2816 // phantom disconnect for this type.
2817 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2818 boolean doRemove = true;
2819 if (wasKept) {
2820 // check if any of the remaining requests for this network are for the
2821 // same legacy type - if so, don't remove the nai
2822 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2823 NetworkRequest otherRequest = nai.requestAt(i);
2824 if (otherRequest.legacyType == nri.request.legacyType &&
2825 otherRequest.isRequest()) {
2826 if (DBG) log(" still have other legacy request - leaving");
2827 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002828 }
2829 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002830 }
2831
Erik Klineacdd6392016-07-07 16:50:58 +09002832 if (doRemove) {
2833 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002834 }
2835 }
Erik Klineacdd6392016-07-07 16:50:58 +09002836
2837 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2838 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2839 nri.request);
2840 }
2841 } else {
2842 // listens don't have a singular affectedNetwork. Check all networks to see
2843 // if this listen request applies and remove it.
2844 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2845 nai.removeRequest(nri.request.requestId);
2846 if (nri.request.networkCapabilities.hasSignalStrength() &&
2847 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2848 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2849 }
2850 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002851 }
2852 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002853
Lorenzo Colitti18660282016-07-04 12:55:44 +09002854 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002855 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2856 enforceConnectivityInternalPermission();
2857 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002858 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002859 }
2860
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002861 @Override
2862 public void setAvoidUnvalidated(Network network) {
2863 enforceConnectivityInternalPermission();
2864 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2865 }
2866
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002867 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2868 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2869 " accept=" + accept + " always=" + always);
2870
2871 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2872 if (nai == null) {
2873 // Nothing to do.
2874 return;
2875 }
2876
2877 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002878 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002879 return;
2880 }
2881
2882 if (!nai.networkMisc.explicitlySelected) {
2883 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2884 }
2885
2886 if (accept != nai.networkMisc.acceptUnvalidated) {
2887 int oldScore = nai.getCurrentScore();
2888 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002889 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002890 sendUpdatedScoreToFactories(nai);
2891 }
2892
2893 if (always) {
2894 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002895 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002896 }
2897
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002898 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002899 // Tell the NetworkAgent to not automatically reconnect to the network.
2900 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09002901 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04002902 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002903 }
2904
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002905 }
2906
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002907 private void handleSetAvoidUnvalidated(Network network) {
2908 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2909 if (nai == null || nai.lastValidated) {
2910 // Nothing to do. The network either disconnected or revalidated.
2911 return;
2912 }
2913 if (!nai.avoidUnvalidated) {
2914 int oldScore = nai.getCurrentScore();
2915 nai.avoidUnvalidated = true;
2916 rematchAllNetworksAndRequests(nai, oldScore);
2917 sendUpdatedScoreToFactories(nai);
2918 }
2919 }
2920
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002921 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002922 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002923 mHandler.sendMessageDelayed(
2924 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2925 PROMPT_UNVALIDATED_DELAY_MS);
2926 }
2927
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002928 @Override
2929 public void startCaptivePortalApp(Network network) {
2930 enforceConnectivityInternalPermission();
2931 mHandler.post(() -> {
2932 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2933 if (nai == null) return;
2934 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2935 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2936 });
2937 }
2938
Hugo Benichic8e9e122016-09-14 23:23:08 +00002939 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002940 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002941 }
2942
Erik Kline065ab6e2016-10-02 18:02:14 +09002943 private void rematchForAvoidBadWifiUpdate() {
2944 rematchAllNetworksAndRequests(null, 0);
2945 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2946 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2947 sendUpdatedScoreToFactories(nai);
2948 }
2949 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002950 }
2951
Erik Kline065ab6e2016-10-02 18:02:14 +09002952 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002953 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002954 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002955 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002956 if (!configRestrict) {
2957 pw.println("Bad Wi-Fi avoidance: unrestricted");
2958 return;
2959 }
2960
2961 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2962 pw.increaseIndent();
2963 pw.println("Config restrict: " + configRestrict);
2964
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002965 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002966 String description;
2967 // Can't use a switch statement because strings are legal case labels, but null is not.
2968 if ("0".equals(value)) {
2969 description = "get stuck";
2970 } else if (value == null) {
2971 description = "prompt";
2972 } else if ("1".equals(value)) {
2973 description = "avoid";
2974 } else {
2975 description = value + " (?)";
2976 }
2977 pw.println("User setting: " + description);
2978 pw.println("Network overrides:");
2979 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09002980 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002981 if (nai.avoidUnvalidated) {
2982 pw.println(nai.name());
2983 }
2984 }
2985 pw.decreaseIndent();
2986 pw.decreaseIndent();
2987 }
2988
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002989 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2990 final String action;
2991 switch (type) {
2992 case NO_INTERNET:
2993 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2994 break;
2995 case LOST_INTERNET:
2996 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2997 break;
2998 default:
2999 Slog.wtf(TAG, "Unknown notification type " + type);
3000 return;
3001 }
3002
3003 Intent intent = new Intent(action);
3004 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3005 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3006 intent.setClassName("com.android.settings",
3007 "com.android.settings.wifi.WifiNoInternetDialog");
3008
3009 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3010 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3011 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3012 }
3013
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003014 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003015 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003016 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3017
3018 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3019 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003020 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003021 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003022 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3023 return;
3024 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003025 showValidationNotification(nai, NotificationType.NO_INTERNET);
3026 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003027
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003028 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3029 NetworkCapabilities nc = nai.networkCapabilities;
3030 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003031
Erik Kline065ab6e2016-10-02 18:02:14 +09003032 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003033 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003034 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3035 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003036 }
3037
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003038 @Override
3039 public int getMultipathPreference(Network network) {
3040 enforceAccessPermission();
3041
3042 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003043 if (nai != null && nai.networkCapabilities
3044 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003045 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3046 }
3047
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003048 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3049 if (networkPreference != null) {
3050 return networkPreference;
3051 }
3052
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003053 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3054 }
3055
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003056 private class InternalHandler extends Handler {
3057 public InternalHandler(Looper looper) {
3058 super(looper);
3059 }
3060
3061 @Override
3062 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003063 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003064 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003065 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003066 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003067 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003068 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003069 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003070 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003071 break;
3072 }
Jason Monkdecd2952013-10-10 14:02:51 -04003073 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003074 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003075 break;
3076 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003077 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003078 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3079 break;
3080 }
3081 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3082 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003083 break;
3084 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003085 case EVENT_REGISTER_NETWORK_AGENT: {
3086 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3087 break;
3088 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003089 case EVENT_REGISTER_NETWORK_REQUEST:
3090 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003091 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003092 break;
3093 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003094 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3095 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003096 handleRegisterNetworkRequestWithIntent(msg);
3097 break;
3098 }
Erik Kline57faba92015-11-25 12:49:38 +09003099 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3100 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3101 handleTimedOutNetworkRequest(nri);
3102 break;
3103 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003104 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3105 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3106 break;
3107 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003108 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003109 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003110 break;
3111 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003112 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003113 Network network = (Network) msg.obj;
3114 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003115 break;
3116 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003117 case EVENT_SET_AVOID_UNVALIDATED: {
3118 handleSetAvoidUnvalidated((Network) msg.obj);
3119 break;
3120 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003121 case EVENT_PROMPT_UNVALIDATED: {
3122 handlePromptUnvalidated((Network) msg.obj);
3123 break;
3124 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003125 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3126 handleMobileDataAlwaysOn();
3127 break;
3128 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003129 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3130 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3131 mKeepaliveTracker.handleStartKeepalive(msg);
3132 break;
3133 }
3134 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3135 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3136 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3137 int slot = msg.arg1;
3138 int reason = msg.arg2;
3139 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3140 break;
3141 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003142 case EVENT_SYSTEM_READY: {
3143 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3144 nai.networkMonitor.systemReady = true;
3145 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003146 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003147 break;
3148 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003149 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003150 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003151 break;
3152 }
Erik Klinea24d4592018-01-11 21:07:29 +09003153 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3154 handlePrivateDnsSettingsChanged();
3155 break;
dalyk7301aa42018-03-05 12:42:22 -05003156 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3157 handlePrivateDnsValidationUpdate(
3158 (PrivateDnsValidationUpdate) msg.obj);
3159 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 }
3161 }
3162 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003163
3164 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003165 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003166 public int tether(String iface, String callerPkg) {
3167 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003168 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003169 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003170 } else {
3171 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3172 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003173 }
3174
3175 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003176 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003177 public int untether(String iface, String callerPkg) {
3178 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003179
3180 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003181 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003182 } else {
3183 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3184 }
3185 }
3186
3187 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003188 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003189 public int getLastTetherError(String iface) {
3190 enforceTetherAccessPermission();
3191
3192 if (isTetheringSupported()) {
3193 return mTethering.getLastTetherError(iface);
3194 } else {
3195 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3196 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003197 }
3198
3199 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003200 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003201 public String[] getTetherableUsbRegexs() {
3202 enforceTetherAccessPermission();
3203 if (isTetheringSupported()) {
3204 return mTethering.getTetherableUsbRegexs();
3205 } else {
3206 return new String[0];
3207 }
3208 }
3209
Lorenzo Colitti18660282016-07-04 12:55:44 +09003210 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003211 public String[] getTetherableWifiRegexs() {
3212 enforceTetherAccessPermission();
3213 if (isTetheringSupported()) {
3214 return mTethering.getTetherableWifiRegexs();
3215 } else {
3216 return new String[0];
3217 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003218 }
3219
Lorenzo Colitti18660282016-07-04 12:55:44 +09003220 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003221 public String[] getTetherableBluetoothRegexs() {
3222 enforceTetherAccessPermission();
3223 if (isTetheringSupported()) {
3224 return mTethering.getTetherableBluetoothRegexs();
3225 } else {
3226 return new String[0];
3227 }
3228 }
3229
Lorenzo Colitti18660282016-07-04 12:55:44 +09003230 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003231 public int setUsbTethering(boolean enable, String callerPkg) {
3232 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003233 if (isTetheringSupported()) {
3234 return mTethering.setUsbTethering(enable);
3235 } else {
3236 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3237 }
3238 }
3239
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003240 // TODO - move iface listing, queries, etc to new module
3241 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003242 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003243 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003244 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003245 return mTethering.getTetherableIfaces();
3246 }
3247
Lorenzo Colitti18660282016-07-04 12:55:44 +09003248 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003249 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003250 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003251 return mTethering.getTetheredIfaces();
3252 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003253
Lorenzo Colitti18660282016-07-04 12:55:44 +09003254 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003255 public String[] getTetheringErroredIfaces() {
3256 enforceTetherAccessPermission();
3257 return mTethering.getErroredIfaces();
3258 }
3259
Lorenzo Colitti18660282016-07-04 12:55:44 +09003260 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003261 public String[] getTetheredDhcpRanges() {
3262 enforceConnectivityInternalPermission();
3263 return mTethering.getTetheredDhcpRanges();
3264 }
3265
Udam Saini0e94c362017-06-07 12:06:28 -07003266 @Override
3267 public boolean isTetheringSupported(String callerPkg) {
3268 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3269 return isTetheringSupported();
3270 }
3271
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003272 // if ro.tether.denied = true we default to no tethering
3273 // gservices could set the secure setting to 1 though to enable it on a build where it
3274 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003275 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003276 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3277 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3278 Settings.Global.TETHER_SUPPORTED, defaultVal));
3279 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003280 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003281
3282 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3283 boolean adminUser = false;
3284 final long token = Binder.clearCallingIdentity();
3285 try {
3286 adminUser = mUserManager.isAdminUser();
3287 } finally {
3288 Binder.restoreCallingIdentity(token);
3289 }
3290
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003291 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003292 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003293
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003294 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003295 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3296 String callerPkg) {
3297 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003298 if (!isTetheringSupported()) {
3299 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3300 return;
3301 }
3302 mTethering.startTethering(type, receiver, showProvisioningUi);
3303 }
3304
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003305 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003306 public void stopTethering(int type, String callerPkg) {
3307 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003308 mTethering.stopTethering(type);
3309 }
3310
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003311 // Called when we lose the default network and have no replacement yet.
3312 // This will automatically be cleared after X seconds or a new default network
3313 // becomes CONNECTED, whichever happens first. The timer is started by the
3314 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003315 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003316 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003317 if (mNetTransitionWakeLock.isHeld()) {
3318 return;
3319 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003320 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003321 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3322 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003323 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003324 mWakelockLogs.log("ACQUIRE for " + forWhom);
3325 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3326 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003327 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003328
Hugo Benichi4c31b342017-03-30 23:18:10 +09003329 // Called when we gain a new default network to release the network transition wakelock in a
3330 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3331 // message is cancelled.
3332 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003333 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003334 if (!mNetTransitionWakeLock.isHeld()) {
3335 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003336 }
3337 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003338 // Cancel self timeout on wakelock hold.
3339 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3340 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3341 mHandler.sendMessageDelayed(msg, 1000);
3342 }
3343
3344 // Called when either message of ensureNetworkTransitionWakelock or
3345 // scheduleReleaseNetworkTransitionWakelock is processed.
3346 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3347 String event = eventName(eventId);
3348 synchronized (this) {
3349 if (!mNetTransitionWakeLock.isHeld()) {
3350 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3351 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3352 return;
3353 }
3354 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003355 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3356 mTotalWakelockDurationMs += lockDuration;
3357 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3358 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003359 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003360 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003361 }
3362
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003363 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003364 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003365 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003366 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003367 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003368 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003369 }
3370
Lorenzo Colitti18660282016-07-04 12:55:44 +09003371 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003372 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003373 enforceAccessPermission();
3374 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003375 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003376 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003377 mHandler.sendMessage(
3378 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3379 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003380
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003381 private void handleReportNetworkConnectivity(
3382 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003383 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003384 if (network == null) {
3385 nai = getDefaultNetwork();
3386 } else {
3387 nai = getNetworkAgentInfoForNetwork(network);
3388 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003389 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3390 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3391 return;
3392 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003393 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003394 if (hasConnectivity == nai.lastValidated) {
3395 return;
3396 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003397 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003398 int netid = nai.network.netId;
3399 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003400 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003401 // Validating a network that has not yet connected could result in a call to
3402 // rematchNetworkAndRequests() which is not meant to work on such networks.
3403 if (!nai.everConnected) {
3404 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003405 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003406 LinkProperties lp = getLinkProperties(nai);
3407 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3408 return;
3409 }
Erik Kline736353a2018-03-21 07:18:33 -07003410 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003411 }
3412
Lorenzo Colitti18660282016-07-04 12:55:44 +09003413 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003414 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003415 if (network == null) return mProxyTracker.getDefaultProxy();
3416 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003417 if (globalProxy != null) return globalProxy;
3418 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3419 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3420 // caller may not have.
3421 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3422 if (nai == null) return null;
3423 synchronized (nai) {
3424 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3425 if (proxyInfo == null) return null;
3426 return new ProxyInfo(proxyInfo);
3427 }
3428 }
3429
Chalard Jean3c443fc2018-06-07 18:37:59 +09003430 @Override
3431 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003432 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003433 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003434 }
3435
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003436 private void loadGlobalProxy() {
3437 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003438 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3439 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3440 String exclList = Settings.Global.getString(res,
3441 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003442 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3443 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003444 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003445 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003446 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003447 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003448 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003449 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003450 if (!proxyProperties.isValid()) {
3451 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3452 return;
3453 }
3454
Chalard Jean52c2aa72018-06-07 16:44:04 +09003455 synchronized (mProxyTracker.mProxyLock) {
3456 mProxyTracker.mGlobalProxy = proxyProperties;
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003457 }
3458 }
3459 }
3460
Chalard Jean5afbc832018-06-07 18:02:37 +09003461 @Override
3462 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003463 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003464 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 }
3466
Jason Monk207900c2014-04-25 15:00:09 -04003467 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003468 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003469 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003470 proxy = null;
3471 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003472 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003473 }
3474
Paul Jensene0bef712014-12-10 15:12:18 -05003475 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3476 // This method gets called when any network changes proxy, but the broadcast only ever contains
3477 // the default proxy (even if it hasn't changed).
3478 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3479 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003480 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003481 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3482 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3483
Chalard Jean4949dd72018-06-07 17:41:29 +09003484 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003485 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003486 }
3487 }
3488
Robert Greenwalt434203a2010-10-11 16:00:27 -07003489 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003490 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003491 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003492 if (!TextUtils.isEmpty(proxy)) {
3493 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003494 if (data.length == 0) {
3495 return;
3496 }
3497
Chalard Jean4133a122018-06-04 13:33:12 +09003498 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003499 int proxyPort = 8080;
3500 if (data.length > 1) {
3501 try {
3502 proxyPort = Integer.parseInt(data[1]);
3503 } catch (NumberFormatException e) {
3504 return;
3505 }
3506 }
Chalard Jean4133a122018-06-04 13:33:12 +09003507 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003508 setGlobalProxy(p);
3509 }
3510 }
3511
Robert Greenwalt434203a2010-10-11 16:00:27 -07003512 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003513 final private HashMap<Uri, Integer> mUriEventMap;
3514 final private Context mContext;
3515 final private Handler mHandler;
3516
3517 SettingsObserver(Context context, Handler handler) {
3518 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003519 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003520 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003521 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003522 }
3523
Erik Klineda4bfa82015-04-30 12:58:40 +09003524 void observe(Uri uri, int what) {
3525 mUriEventMap.put(uri, what);
3526 final ContentResolver resolver = mContext.getContentResolver();
3527 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003528 }
3529
3530 @Override
3531 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003532 Slog.wtf(TAG, "Should never be reached.");
3533 }
3534
3535 @Override
3536 public void onChange(boolean selfChange, Uri uri) {
3537 final Integer what = mUriEventMap.get(uri);
3538 if (what != null) {
3539 mHandler.obtainMessage(what.intValue()).sendToTarget();
3540 } else {
3541 loge("No matching event to send for URI=" + uri);
3542 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003543 }
3544 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003545
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003546 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003547 Slog.d(TAG, s);
3548 }
3549
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003550 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003551 Slog.e(TAG, s);
3552 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003553
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003554 private static void loge(String s, Throwable t) {
3555 Slog.e(TAG, s, t);
3556 }
3557
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003558 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003559 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003560 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3561 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3562 *
3563 * @param oldPackage Package name of the application which currently controls VPN, which will
3564 * be replaced. If there is no such application, this should should either be
3565 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3566 * @param newPackage Package name of the application which should gain control of VPN, or
3567 * {@code null} to disable.
3568 * @param userId User for whom to prepare the new VPN.
3569 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003570 * @hide
3571 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003572 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003573 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3574 int userId) {
3575 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003576
Hugo Benichi20035e02017-04-26 14:53:28 +09003577 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003578 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003579 Vpn vpn = mVpns.get(userId);
3580 if (vpn != null) {
3581 return vpn.prepare(oldPackage, newPackage);
3582 } else {
3583 return false;
3584 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003585 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003586 }
3587
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003588 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003589 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3590 * This method is used by system-privileged apps.
3591 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3592 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3593 *
3594 * @param packageName The package for which authorization state should change.
3595 * @param userId User for whom {@code packageName} is installed.
3596 * @param authorized {@code true} if this app should be able to start a VPN connection without
3597 * explicit user approval, {@code false} if not.
3598 *
Jeff Davidson05542602014-08-11 14:07:27 -07003599 * @hide
3600 */
3601 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003602 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3603 enforceCrossUserPermission(userId);
3604
Hugo Benichi20035e02017-04-26 14:53:28 +09003605 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003606 Vpn vpn = mVpns.get(userId);
3607 if (vpn != null) {
3608 vpn.setPackageAuthorization(packageName, authorized);
3609 }
Jeff Davidson05542602014-08-11 14:07:27 -07003610 }
3611 }
3612
3613 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003614 * Configure a TUN interface and return its file descriptor. Parameters
3615 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003616 * and not available in ConnectivityManager. Permissions are checked in
3617 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003618 * @hide
3619 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003620 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003621 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003622 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003623 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003624 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003625 return mVpns.get(user).establish(config);
3626 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003627 }
3628
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003629 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003630 * Start legacy VPN, controlling native daemons as needed. Creates a
3631 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003632 */
3633 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003634 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003635 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003636 final LinkProperties egress = getActiveLinkProperties();
3637 if (egress == null) {
3638 throw new IllegalStateException("Missing active network connection");
3639 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003640 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003641 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003642 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3643 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003644 }
3645
3646 /**
3647 * Return the information of the ongoing legacy VPN. This method is used
3648 * by VpnSettings and not available in ConnectivityManager. Permissions
3649 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003650 */
3651 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003652 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3653 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003654
Hugo Benichi20035e02017-04-26 14:53:28 +09003655 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003656 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003657 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003658 }
3659
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003660 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003661 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3662 * and not available in ConnectivityManager.
3663 */
3664 @Override
3665 public VpnInfo[] getAllVpnInfo() {
3666 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003667 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003668 if (mLockdownEnabled) {
3669 return new VpnInfo[0];
3670 }
3671
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003672 List<VpnInfo> infoList = new ArrayList<>();
3673 for (int i = 0; i < mVpns.size(); i++) {
3674 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3675 if (info != null) {
3676 infoList.add(info);
3677 }
3678 }
3679 return infoList.toArray(new VpnInfo[infoList.size()]);
3680 }
3681 }
3682
3683 /**
3684 * @return VPN information for accounting, or null if we can't retrieve all required
3685 * information, e.g primary underlying iface.
3686 */
3687 @Nullable
3688 private VpnInfo createVpnInfo(Vpn vpn) {
3689 VpnInfo info = vpn.getVpnInfo();
3690 if (info == null) {
3691 return null;
3692 }
3693 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3694 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3695 // the underlyingNetworks list.
3696 if (underlyingNetworks == null) {
3697 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3698 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3699 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3700 }
3701 } else if (underlyingNetworks.length > 0) {
3702 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3703 if (linkProperties != null) {
3704 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3705 }
3706 }
3707 return info.primaryUnderlyingIface == null ? null : info;
3708 }
3709
3710 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003711 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3712 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003713 * Permissions are checked in Vpn class.
3714 * @hide
3715 */
3716 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003717 public VpnConfig getVpnConfig(int userId) {
3718 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003719 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003720 Vpn vpn = mVpns.get(userId);
3721 if (vpn != null) {
3722 return vpn.getVpnConfig();
3723 } else {
3724 return null;
3725 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003726 }
3727 }
3728
Chalard Jean6b65ec72018-05-18 22:02:56 +09003729 /**
3730 * Ask all VPN objects to recompute and update their capabilities.
3731 *
3732 * When underlying networks change, VPNs may have to update capabilities to reflect things
3733 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3734 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3735 * handler thread through their agent, this is asynchronous. When the capabilities objects
3736 * are computed they will be up-to-date as they are computed synchronously from here and
3737 * this is running on the ConnectivityService thread.
3738 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3739 */
3740 private void updateAllVpnsCapabilities() {
3741 synchronized (mVpns) {
3742 for (int i = 0; i < mVpns.size(); i++) {
3743 final Vpn vpn = mVpns.valueAt(i);
3744 vpn.updateCapabilities();
3745 }
3746 }
3747 }
3748
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003749 @Override
3750 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003751 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3752 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3753 return false;
3754 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003755
Hugo Benichi69744342017-11-27 10:57:16 +09003756 synchronized (mVpns) {
3757 // Tear down existing lockdown if profile was removed
3758 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3759 if (mLockdownEnabled) {
3760 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3761 if (profileTag == null) {
3762 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3763 return false;
3764 }
3765 String profileName = new String(profileTag);
3766 final VpnProfile profile = VpnProfile.decode(
3767 profileName, mKeyStore.get(Credentials.VPN + profileName));
3768 if (profile == null) {
3769 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3770 setLockdownTracker(null);
3771 return true;
3772 }
3773 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003774 Vpn vpn = mVpns.get(user);
3775 if (vpn == null) {
3776 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3777 return false;
3778 }
Luke Huang4e25ec62018-09-27 16:58:23 +08003779 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003780 } else {
3781 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003782 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003783 }
3784
3785 return true;
3786 }
3787
3788 /**
3789 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3790 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3791 */
Hugo Benichi69744342017-11-27 10:57:16 +09003792 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003793 private void setLockdownTracker(LockdownVpnTracker tracker) {
3794 // Shutdown any existing tracker
3795 final LockdownVpnTracker existing = mLockdownTracker;
3796 mLockdownTracker = null;
3797 if (existing != null) {
3798 existing.shutdown();
3799 }
3800
Robin Leec3736bc2017-03-10 16:19:54 +00003801 if (tracker != null) {
3802 mLockdownTracker = tracker;
3803 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003804 }
3805 }
3806
Hugo Benichi69744342017-11-27 10:57:16 +09003807 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003808 private void throwIfLockdownEnabled() {
3809 if (mLockdownEnabled) {
3810 throw new IllegalStateException("Unavailable in lockdown mode");
3811 }
3812 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003813
Robin Lee244ce8e2016-01-05 18:03:46 +00003814 /**
Robin Lee17e61832016-05-09 13:46:28 +01003815 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3816 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003817 *
Robin Lee17e61832016-05-09 13:46:28 +01003818 * @return {@code true} if the service was started, the service was already connected, or there
3819 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003820 */
Robin Lee17e61832016-05-09 13:46:28 +01003821 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003822 synchronized (mVpns) {
3823 Vpn vpn = mVpns.get(userId);
3824 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003825 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003826 // exists already.
3827 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3828 return false;
3829 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003830
Robin Lee812800c2016-05-13 15:38:08 +01003831 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003832 }
3833 }
3834
3835 @Override
Charles He36738632017-05-15 17:07:18 +01003836 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3837 enforceSettingsPermission();
3838 enforceCrossUserPermission(userId);
3839
3840 synchronized (mVpns) {
3841 Vpn vpn = mVpns.get(userId);
3842 if (vpn == null) {
3843 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3844 return false;
3845 }
3846 return vpn.isAlwaysOnPackageSupported(packageName);
3847 }
3848 }
3849
3850 @Override
Robin Leedc679712016-05-03 13:23:03 +01003851 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003852 enforceConnectivityInternalPermission();
3853 enforceCrossUserPermission(userId);
3854
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003856 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3857 if (LockdownVpnTracker.isEnabled()) {
3858 return false;
3859 }
3860
Robin Lee244ce8e2016-01-05 18:03:46 +00003861 Vpn vpn = mVpns.get(userId);
3862 if (vpn == null) {
3863 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3864 return false;
3865 }
Robin Lee17e61832016-05-09 13:46:28 +01003866 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003867 return false;
3868 }
Robin Lee17e61832016-05-09 13:46:28 +01003869 if (!startAlwaysOnVpn(userId)) {
3870 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003871 return false;
3872 }
3873 }
3874 return true;
3875 }
3876
3877 @Override
3878 public String getAlwaysOnVpnPackage(int userId) {
3879 enforceConnectivityInternalPermission();
3880 enforceCrossUserPermission(userId);
3881
3882 synchronized (mVpns) {
3883 Vpn vpn = mVpns.get(userId);
3884 if (vpn == null) {
3885 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3886 return null;
3887 }
3888 return vpn.getAlwaysOnPackage();
3889 }
3890 }
3891
Wink Savilleab9321d2013-06-29 21:10:57 -07003892 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003893 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003894 // TODO: Remove? Any reason to trigger a provisioning check?
3895 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003896 }
3897
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003898 /** Location to an updatable file listing carrier provisioning urls.
3899 * An example:
3900 *
3901 * <?xml version="1.0" encoding="utf-8"?>
3902 * <provisioningUrls>
3903 * <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 -07003904 * </provisioningUrls>
3905 */
3906 private static final String PROVISIONING_URL_PATH =
3907 "/data/misc/radio/provisioning_urls.xml";
3908 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003909
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003910 /** XML tag for root element. */
3911 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3912 /** XML tag for individual url */
3913 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003914 /** XML attribute for mcc */
3915 private static final String ATTR_MCC = "mcc";
3916 /** XML attribute for mnc */
3917 private static final String ATTR_MNC = "mnc";
3918
Paul Jensen434dde82015-06-11 09:43:30 -04003919 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003920 FileReader fileReader = null;
3921 XmlPullParser parser = null;
3922 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003923
3924 try {
3925 fileReader = new FileReader(mProvisioningUrlFile);
3926 parser = Xml.newPullParser();
3927 parser.setInput(fileReader);
3928 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3929
3930 while (true) {
3931 XmlUtils.nextElement(parser);
3932
3933 String element = parser.getName();
3934 if (element == null) break;
3935
Paul Jensen434dde82015-06-11 09:43:30 -04003936 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003937 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3938 try {
3939 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3940 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3941 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3942 parser.next();
3943 if (parser.getEventType() == XmlPullParser.TEXT) {
3944 return parser.getText();
3945 }
3946 }
3947 }
3948 } catch (NumberFormatException e) {
3949 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3950 }
3951 }
3952 }
3953 return null;
3954 } catch (FileNotFoundException e) {
3955 loge("Carrier Provisioning Urls file not found");
3956 } catch (XmlPullParserException e) {
3957 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3958 } catch (IOException e) {
3959 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3960 } finally {
3961 if (fileReader != null) {
3962 try {
3963 fileReader.close();
3964 } catch (IOException e) {}
3965 }
3966 }
3967 return null;
3968 }
3969
Wink Saville42d4f082013-07-20 20:31:59 -07003970 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003971 public String getMobileProvisioningUrl() {
3972 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003973 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003974 if (TextUtils.isEmpty(url)) {
3975 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003976 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003977 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003978 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003979 }
Wink Saville8cf35602013-07-10 23:00:07 -07003980 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003981 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003982 String phoneNumber = mTelephonyManager.getLine1Number();
3983 if (TextUtils.isEmpty(phoneNumber)) {
3984 phoneNumber = "0000000000";
3985 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003986 url = String.format(url,
3987 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3988 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09003989 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003990 }
3991
Wink Savilleab9321d2013-06-29 21:10:57 -07003992 return url;
3993 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003994
Wink Saville948282b2013-08-29 08:55:16 -07003995 @Override
3996 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003997 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003998 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003999 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4000 return;
4001 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004002 final long ident = Binder.clearCallingIdentity();
4003 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004004 // Concatenate the range of types onto the range of NetIDs.
4005 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4006 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004007 } finally {
4008 Binder.restoreCallingIdentity(ident);
4009 }
Wink Saville948282b2013-08-29 08:55:16 -07004010 }
Wink Saville7788c612013-08-29 14:57:08 -07004011
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004012 @Override
4013 public void setAirplaneMode(boolean enable) {
4014 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004015 final long ident = Binder.clearCallingIdentity();
4016 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004017 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004018 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004019 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4020 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004021 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004022 } finally {
4023 Binder.restoreCallingIdentity(ident);
4024 }
4025 }
4026
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004027 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004028 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004029 Vpn userVpn = mVpns.get(userId);
4030 if (userVpn != null) {
4031 loge("Starting user already has a VPN");
4032 return;
4033 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004034 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004035 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004036 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4037 updateLockdownVpn();
4038 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004039 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004040 }
4041
4042 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004043 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004044 Vpn userVpn = mVpns.get(userId);
4045 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004046 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004047 return;
4048 }
Robin Lee17e61832016-05-09 13:46:28 +01004049 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004050 mVpns.delete(userId);
4051 }
4052 }
4053
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004054 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004055 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004056 final int vpnsSize = mVpns.size();
4057 for (int i = 0; i < vpnsSize; i++) {
4058 Vpn vpn = mVpns.valueAt(i);
4059 vpn.onUserAdded(userId);
4060 }
4061 }
4062 }
4063
4064 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004065 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004066 final int vpnsSize = mVpns.size();
4067 for (int i = 0; i < vpnsSize; i++) {
4068 Vpn vpn = mVpns.valueAt(i);
4069 vpn.onUserRemoved(userId);
4070 }
4071 }
4072 }
4073
Robin Lee89e7a692016-02-29 14:38:17 +00004074 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004075 synchronized (mVpns) {
4076 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4077 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4078 updateLockdownVpn();
4079 } else {
4080 startAlwaysOnVpn(userId);
4081 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004082 }
4083 }
4084
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004085 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4086 @Override
4087 public void onReceive(Context context, Intent intent) {
4088 final String action = intent.getAction();
4089 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4090 if (userId == UserHandle.USER_NULL) return;
4091
Robin Lee323f29d2016-05-04 16:38:06 +01004092 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004093 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004094 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004095 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004096 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4097 onUserAdded(userId);
4098 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4099 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004100 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4101 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004102 }
4103 }
4104 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004105
Robin Lee95204e02017-01-27 11:59:22 +00004106 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4107 @Override
4108 public void onReceive(Context context, Intent intent) {
4109 // Try creating lockdown tracker, since user present usually means
4110 // unlocked keystore.
4111 updateLockdownVpn();
4112 mContext.unregisterReceiver(this);
4113 }
4114 };
4115
Chalard Jean4133a122018-06-04 13:33:12 +09004116 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4117 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004118
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004119 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4120 // Map from UID to number of NetworkRequests that UID has filed.
4121 @GuardedBy("mUidToNetworkRequestCount")
4122 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4123
Robert Greenwalta67be032014-05-16 15:49:14 -07004124 private static class NetworkFactoryInfo {
4125 public final String name;
4126 public final Messenger messenger;
4127 public final AsyncChannel asyncChannel;
4128
4129 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4130 this.name = name;
4131 this.messenger = messenger;
4132 this.asyncChannel = asyncChannel;
4133 }
4134 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004135
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004136 private void ensureNetworkRequestHasType(NetworkRequest request) {
4137 if (request.type == NetworkRequest.Type.NONE) {
4138 throw new IllegalArgumentException(
4139 "All NetworkRequests in ConnectivityService must have a type");
4140 }
4141 }
4142
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004143 /**
4144 * Tracks info about the requester.
4145 * Also used to notice when the calling process dies so we can self-expire
4146 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004150 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004151 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152 final int mPid;
4153 final int mUid;
4154 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004156 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004157 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004158 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004159 mPendingIntent = pi;
4160 messenger = null;
4161 mBinder = null;
4162 mPid = getCallingPid();
4163 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004164 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004165 }
4166
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004167 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 super();
4169 messenger = m;
4170 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004171 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 mBinder = binder;
4173 mPid = getCallingPid();
4174 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004175 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004176 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177
4178 try {
4179 mBinder.linkToDeath(this, 0);
4180 } catch (RemoteException e) {
4181 binderDied();
4182 }
4183 }
4184
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004185 private void enforceRequestCountLimit() {
4186 synchronized (mUidToNetworkRequestCount) {
4187 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4188 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004189 throw new ServiceSpecificException(
4190 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004191 }
4192 mUidToNetworkRequestCount.put(mUid, networkRequests);
4193 }
4194 }
4195
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 if (mBinder != null) {
4198 mBinder.unlinkToDeath(this, 0);
4199 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004200 }
4201
4202 public void binderDied() {
4203 log("ConnectivityService NetworkRequestInfo binderDied(" +
4204 request + ", " + mBinder + ")");
4205 releaseNetworkRequest(request);
4206 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004207
4208 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004209 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004210 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004211 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004212 }
4213
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004214 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4215 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4216 if (badCapability != null) {
4217 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004218 }
4219 }
4220
Chalard Jeanb03a6222018-04-11 21:09:10 +09004221 // This checks that the passed capabilities either do not request a specific SSID, or the
4222 // calling app has permission to do so.
4223 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4224 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004225 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004226 throw new SecurityException("Insufficient permissions to request a specific SSID");
4227 }
4228 }
4229
Erik Kline9d598e12015-07-13 16:37:51 +09004230 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004231 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004232 synchronized (nai) {
4233 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4234 if (nri.request.networkCapabilities.hasSignalStrength() &&
4235 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4236 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4237 }
4238 }
4239 }
Chalard Jean4133a122018-06-04 13:33:12 +09004240 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004241 }
4242
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004243 private void updateSignalStrengthThresholds(
4244 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4245 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004246 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004247 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4248
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004249 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004250 String detail;
4251 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4252 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4253 } else {
4254 detail = reason;
4255 }
4256 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4257 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4258 }
4259
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004260 nai.asyncChannel.sendMessage(
4261 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004262 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004263 }
4264
Etan Cohen859748f2017-04-03 17:42:34 -07004265 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4266 if (nc == null) {
4267 return;
4268 }
4269 NetworkSpecifier ns = nc.getNetworkSpecifier();
4270 if (ns == null) {
4271 return;
4272 }
4273 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4274 ns.assertValidFromUid(Binder.getCallingUid());
4275 }
4276
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 @Override
4278 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004279 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004280 final NetworkRequest.Type type = (networkCapabilities == null)
4281 ? NetworkRequest.Type.TRACK_DEFAULT
4282 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004283 // If the requested networkCapabilities is null, take them instead from
4284 // the default network request. This allows callers to keep track of
4285 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004286 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004287 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004288 enforceAccessPermission();
4289 } else {
4290 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4291 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004292 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4293 // of the app when the request is filed, but we never change the request if the app
4294 // changes network state. http://b/29964605
4295 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004296 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004297 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004298 ensureSufficientPermissionsForRequest(networkCapabilities,
4299 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004300 // Set the UID range for this request to the single UID of the requester, or to an empty
4301 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004302 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4303 // are no visible methods to set the UIDs, an app could use reflection to try and get
4304 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004305 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004306
Etan Cohenba07c8c2017-02-05 10:42:27 -08004307 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004308 throw new IllegalArgumentException("Bad timeout specified");
4309 }
Etan Cohen859748f2017-04-03 17:42:34 -07004310 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004311
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004312 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004313 nextNetworkRequestId(), type);
4314 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004315 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004316
4317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004318 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004320 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321 }
4322 return networkRequest;
4323 }
4324
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004325 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004326 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004327 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004328 } else {
4329 enforceChangePermission();
4330 }
4331 }
4332
fenglub15e72b2015-03-20 11:29:56 -07004333 @Override
fengludb571472015-04-21 17:12:05 -07004334 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004335 enforceAccessPermission();
4336 NetworkAgentInfo nai = null;
4337 if (network == null) {
4338 return false;
4339 }
4340 synchronized (mNetworkForNetId) {
4341 nai = mNetworkForNetId.get(network.netId);
4342 }
4343 if (nai != null) {
4344 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004345 synchronized (mBandwidthRequests) {
4346 final int uid = Binder.getCallingUid();
4347 Integer uidReqs = mBandwidthRequests.get(uid);
4348 if (uidReqs == null) {
4349 uidReqs = new Integer(0);
4350 }
4351 mBandwidthRequests.put(uid, ++uidReqs);
4352 }
fenglub15e72b2015-03-20 11:29:56 -07004353 return true;
4354 }
4355 return false;
4356 }
4357
Felipe Lemeee27cab2016-06-20 16:36:29 -07004358 private boolean isSystem(int uid) {
4359 return uid < Process.FIRST_APPLICATION_UID;
4360 }
fenglub15e72b2015-03-20 11:29:56 -07004361
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004362 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004363 final int uid = Binder.getCallingUid();
4364 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004365 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004366 return;
4367 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004368 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4369 // Policy already enforced.
4370 return;
4371 }
4372 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4373 // If UID is restricted, don't allow them to bring up metered APNs.
4374 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004375 }
4376 }
4377
Robert Greenwalt9258c642014-03-26 16:47:06 -07004378 @Override
4379 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4380 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004381 checkNotNull(operation, "PendingIntent cannot be null.");
4382 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4383 enforceNetworkRequestPermissions(networkCapabilities);
4384 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004385 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004386 ensureSufficientPermissionsForRequest(networkCapabilities,
4387 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004388 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004389 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004390
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004391 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004392 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4393 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004394 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004395 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4396 nri));
4397 return networkRequest;
4398 }
4399
Jeremy Joslin79294842014-12-03 17:15:28 -08004400 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4401 mHandler.sendMessageDelayed(
4402 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4403 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4404 }
4405
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004406 @Override
4407 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004408 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004409 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4410 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004411 }
4412
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004413 // In order to implement the compatibility measure for pre-M apps that call
4414 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4415 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4416 // This ensures it has permission to do so.
4417 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4418 if (nc == null) {
4419 return false;
4420 }
4421 int[] transportTypes = nc.getTransportTypes();
4422 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4423 return false;
4424 }
4425 try {
4426 mContext.enforceCallingOrSelfPermission(
4427 android.Manifest.permission.ACCESS_WIFI_STATE,
4428 "ConnectivityService");
4429 } catch (SecurityException e) {
4430 return false;
4431 }
4432 return true;
4433 }
4434
Robert Greenwalt9258c642014-03-26 16:47:06 -07004435 @Override
4436 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4437 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004438 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4439 enforceAccessPermission();
4440 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004441
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004442 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004443 ensureSufficientPermissionsForRequest(networkCapabilities,
4444 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004445 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004446 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4447 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4448 // onLost and onAvailable callbacks when networks move in and out of the background.
4449 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4450 // can't request networks.
4451 restrictBackgroundRequestForCaller(nc);
4452 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004453
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004454 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004455 NetworkRequest.Type.LISTEN);
4456 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004457 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004458
4459 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4460 return networkRequest;
4461 }
4462
4463 @Override
4464 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4465 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004466 checkNotNull(operation, "PendingIntent cannot be null.");
4467 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4468 enforceAccessPermission();
4469 }
Etan Cohen859748f2017-04-03 17:42:34 -07004470 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004471 ensureSufficientPermissionsForRequest(networkCapabilities,
4472 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004473
Chalard Jeandda156a2018-01-10 21:19:32 +09004474 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004475 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004476
4477 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004478 NetworkRequest.Type.LISTEN);
4479 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004480 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004481
4482 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004483 }
4484
Erik Klineacdd6392016-07-07 16:50:58 +09004485 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004486 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004487 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004488 mHandler.sendMessage(mHandler.obtainMessage(
4489 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490 }
4491
4492 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004493 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004494 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004495 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004497 }
4498
Robert Greenwalta67be032014-05-16 15:49:14 -07004499 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004500 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004501 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4502 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4503 }
4504
4505 @Override
4506 public void unregisterNetworkFactory(Messenger messenger) {
4507 enforceConnectivityInternalPermission();
4508 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4509 }
4510
4511 private void handleUnregisterNetworkFactory(Messenger messenger) {
4512 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4513 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004514 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004515 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004516 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004517 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004518 }
4519
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 /**
4521 * NetworkAgentInfo supporting a request by requestId.
4522 * These have already been vetted (their Capabilities satisfy the request)
4523 * and the are the highest scored network available.
4524 * the are keyed off the Requests requestId.
4525 */
Hugo Benichicd952782017-09-20 11:20:14 +09004526 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4527 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004528 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004529
Paul Jensen31a94f42015-02-13 14:18:39 -05004530 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4531 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004532 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004533 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4534 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4535 // there may not be a strict 1:1 correlation between the two.
4536 @GuardedBy("mNetworkForNetId")
4537 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004538
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 // NetworkAgentInfo keyed off its connecting messenger
4540 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004541 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004542 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004544 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004545 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004546
Paul Jensen2c311d62014-11-17 12:34:51 -05004547 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004548 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004549
Erik Klineda4bfa82015-04-30 12:58:40 +09004550 // Request used to optionally keep mobile data active even when higher
4551 // priority networks like Wi-Fi are active.
4552 private final NetworkRequest mDefaultMobileDataRequest;
4553
Hugo Benichicd952782017-09-20 11:20:14 +09004554 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4555 synchronized (mNetworkForRequestId) {
4556 return mNetworkForRequestId.get(requestId);
4557 }
4558 }
4559
4560 private void clearNetworkForRequest(int requestId) {
4561 synchronized (mNetworkForRequestId) {
4562 mNetworkForRequestId.remove(requestId);
4563 }
4564 }
4565
4566 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4567 synchronized (mNetworkForRequestId) {
4568 mNetworkForRequestId.put(requestId, nai);
4569 }
4570 }
4571
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004572 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004573 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004574 }
4575
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004576 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004577 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004578 }
4579
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004580 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4581 return nri.request.requestId == mDefaultRequest.requestId;
4582 }
4583
Paul Jensen31a94f42015-02-13 14:18:39 -05004584 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004585 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004586 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 enforceConnectivityInternalPermission();
4588
Rubin Xu1bb5c082017-09-05 18:40:49 +01004589 LinkProperties lp = new LinkProperties(linkProperties);
4590 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004591 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4592 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004593 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004594 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004595 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004596 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004597 // Make sure the network capabilities reflect what the agent info says.
4598 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004599 synchronized (this) {
4600 nai.networkMonitor.systemReady = mSystemReady;
4601 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004602 final String extraInfo = networkInfo.getExtraInfo();
4603 final String name = TextUtils.isEmpty(extraInfo)
4604 ? nai.networkCapabilities.getSSID() : extraInfo;
4605 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004606 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004607 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004608 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004609 }
4610
Erik Klinee5dac902018-03-04 21:01:01 +09004611 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004612 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004613 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004614 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004615 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004616 }
Erik Klinee5dac902018-03-04 21:01:01 +09004617 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4618 NetworkInfo networkInfo = nai.networkInfo;
4619 nai.networkInfo = null;
4620 updateNetworkInfo(nai, networkInfo);
4621 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004622 }
4623
4624 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004625 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004626 int netId = networkAgent.network.netId;
4627
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004628 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4629 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004630 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004631 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004632 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004633
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004634 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635 updateMtu(newLp, oldLp);
4636 // TODO - figure out what to do for clat
4637// for (LinkProperties lp : newLp.getStackedLinks()) {
4638// updateMtu(lp, null);
4639// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004640 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004641
Erik Kline94887872016-04-05 13:30:49 +09004642 updateRoutes(newLp, oldLp, netId);
4643 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004644 // Make sure LinkProperties represents the latest private DNS status.
4645 // This does not need to be done before updateDnses because the
4646 // LinkProperties are not the source of the private DNS configuration.
4647 // updateDnses will fetch the private DNS configuration from DnsManager.
4648 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004649
Hugo Benichi6f62b732017-06-27 15:13:20 +09004650 // Start or stop clat accordingly to network state.
Luke Huang4e25ec62018-09-27 16:58:23 +08004651 networkAgent.updateClat(mNMS);
Paul Jensene0bef712014-12-10 15:12:18 -05004652 if (isDefaultNetwork(networkAgent)) {
4653 handleApplyDefaultProxy(newLp.getHttpProxy());
4654 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004655 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004656 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004657 // TODO - move this check to cover the whole function
4658 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004659 synchronized (networkAgent) {
4660 networkAgent.linkProperties = newLp;
4661 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004662 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004663 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4664 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004665
4666 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004667 }
4668
Joel Scherpelz668370b2017-06-08 15:35:21 +09004669 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004670 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004671 // marks on unsupported interfaces is harmless.
4672 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4673 return;
4674 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004675
Joel Scherpelz668370b2017-06-08 15:35:21 +09004676 int mark = mContext.getResources().getInteger(
4677 com.android.internal.R.integer.config_networkWakeupPacketMark);
4678 int mask = mContext.getResources().getInteger(
4679 com.android.internal.R.integer.config_networkWakeupPacketMask);
4680
4681 // Mask/mark of zero will not detect anything interesting.
4682 // Don't install rules unless both values are nonzero.
4683 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004684 return;
4685 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004686
4687 final String prefix = "iface:" + iface;
4688 try {
4689 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08004690 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004691 } else {
Luke Huang674660f2018-09-27 19:33:11 +08004692 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004693 }
4694 } catch (Exception e) {
4695 loge("Exception modifying wakeup packet monitoring: " + e);
4696 }
4697
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004698 }
4699
4700 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4701 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004702 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004703 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4704 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004705 for (String iface : interfaceDiff.added) {
4706 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004707 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08004708 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004709 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004710 } catch (Exception e) {
4711 loge("Exception adding interface: " + e);
4712 }
4713 }
4714 for (String iface : interfaceDiff.removed) {
4715 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004716 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004717 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08004718 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004719 } catch (Exception e) {
4720 loge("Exception removing interface: " + e);
4721 }
4722 }
4723 }
4724
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004725 /**
4726 * Have netd update routes from oldLp to newLp.
4727 * @return true if routes changed between oldLp and newLp
4728 */
4729 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004730 // Compare the route diff to determine which routes should be added and removed.
4731 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4732 oldLp != null ? oldLp.getAllRoutes() : null,
4733 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004734
4735 // add routes before removing old in case it helps with continuous connectivity
4736
Chalard Jean4d660112018-06-04 16:52:49 +09004737 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 for (RouteInfo route : routeDiff.added) {
4739 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004740 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004741 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004742 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004744 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4745 loge("Exception in addRoute for non-gateway: " + e);
4746 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004747 }
4748 }
4749 for (RouteInfo route : routeDiff.added) {
4750 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004751 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004752 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004753 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004755 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4756 loge("Exception in addRoute for gateway: " + e);
4757 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004758 }
4759 }
4760
4761 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004762 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004763 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004764 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 } catch (Exception e) {
4766 loge("Exception in removeRoute: " + e);
4767 }
4768 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004769 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 }
Erik Kline41368502015-06-17 13:19:54 +09004771
Erik Kline94887872016-04-05 13:30:49 +09004772 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4773 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4774 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004775 }
Erik Kline94887872016-04-05 13:30:49 +09004776
Erik Kline1742fe12017-12-13 19:40:49 +09004777 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4778 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4779
Erik Klinea24d4592018-01-11 21:07:29 +09004780 if (DBG) {
4781 final Collection<InetAddress> dnses = newLp.getDnsServers();
4782 log("Setting DNS servers for network " + netId + " to " + dnses);
4783 }
Erik Kline94887872016-04-05 13:30:49 +09004784 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004785 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004786 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004787 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004788 }
Erik Kline4edba012017-04-07 15:29:29 +09004789 }
4790
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004791 private String getNetworkPermission(NetworkCapabilities nc) {
4792 // TODO: make these permission strings AIDL constants instead.
4793 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4794 return NetworkManagementService.PERMISSION_SYSTEM;
4795 }
4796 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4797 return NetworkManagementService.PERMISSION_NETWORK;
4798 }
4799 return null;
4800 }
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
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004872 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004873 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004874 if (!Objects.equals(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}