blob: e41a09ef672e3f09781446520111f6d38d020a4a [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;
60import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070061import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.INetworkPolicyListener;
63import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070064import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080065import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070066import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010067import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070068import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070069import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070071import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070073import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070074import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090075import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070076import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070077import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070078import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070079import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070080import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000081import android.net.NetworkWatchlistManager;
Jason Monk207900c2014-04-25 15:00:09 -040082import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070083import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040084import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040085import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060086import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090087import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090088import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070089import android.net.netlink.InetDiagMessage;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090090import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080092import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070093import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040094import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070096import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070098import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Looper;
100import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700101import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700102import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900103import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700104import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700105import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800107import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900108import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900109import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700110import android.os.ShellCallback;
111import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900112import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700113import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400114import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700116import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700117import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900120import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700121import android.util.LocalLog;
122import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600123import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800124import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700125import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500126import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
Wink Savilleab9321d2013-06-29 21:10:57 -0700130import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400131import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400132import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700133import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700134import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700135import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800136import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700137import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900138import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700139import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600140import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700141import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900142import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900143import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700144import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700145import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400146import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900147import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900148import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500149import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900150import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900151import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100152import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700153import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900154import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700155import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600156import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400157import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900158import com.android.server.connectivity.NetworkNotificationManager;
159import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700160import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900161import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800162import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700163import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100164import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500165import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700166import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700167import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900168import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700169import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700171import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700172
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700173import org.xmlpull.v1.XmlPullParser;
174import org.xmlpull.v1.XmlPullParserException;
175
176import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700178import java.io.FileNotFoundException;
179import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700180import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700182import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700183import java.net.InetAddress;
184import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700185import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700186import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700187import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700188import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900189import java.util.Comparator;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700190import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700191import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700192import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700193import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700194import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900195import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600196import java.util.SortedSet;
197import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
199/**
200 * @hide
201 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800202public class ConnectivityService extends IConnectivityManager.Stub
203 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900204 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Chalard Jean4133a122018-06-04 13:33:12 +0900206 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900207 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900208 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900209 private static final String NETWORK_ARG = "networks";
210 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900211
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900212 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700213 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900215 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700216
Jeff Sharkey899223b2012-08-04 15:24:58 -0700217 // TODO: create better separation between radio types and network types
218
Robert Greenwalt42acef32009-08-12 16:08:25 -0700219 // how long to wait before switching back to a radio's default network
220 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
221 // system property that can override the above value
222 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
223 "android.telephony.apn-restore";
224
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900225 // How long to wait before putting up a "This network doesn't have an Internet connection,
226 // connect anyway?" dialog after the user selects a network that doesn't validate.
227 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
228
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900229 // Default to 30s linger time-out. Modifiable only for testing.
230 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
231 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
232 @VisibleForTesting
233 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
234
Jeremy Joslin79294842014-12-03 17:15:28 -0800235 // How long to delay to removal of a pending intent based request.
236 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
237 private final int mReleasePendingIntentDelayMs;
238
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900239 private MockableSystemProperties mSystemProperties;
240
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800241 private Tethering mTethering;
242
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700243 private final PermissionMonitor mPermissionMonitor;
244
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700245 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700246
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900247 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700248 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900249 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700250
Hugo Benichi69744342017-11-27 10:57:16 +0900251 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
252 // a direct call to LockdownVpnTracker.isEnabled().
253 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700254 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900255 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700256 private LockdownVpnTracker mLockdownTracker;
257
Erik Klineda4bfa82015-04-30 12:58:40 +0900258 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700259 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700260 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700262 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800263 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700264 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900265 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700266
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700267 private String mCurrentTcpBufferSizes;
268
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900269 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900270 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
271 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900272
Paul Jensenb10e37f2014-11-25 12:33:08 -0500273 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400274 // Tear down networks that have no chance (e.g. even if validated) of becoming
275 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 // all networks have been rematched against all NetworkRequests.
277 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400278 // Don't reap networks. This should be passed when some networks have not yet been
279 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500280 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900281 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500282
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900283 private enum UnneededFor {
284 LINGER, // Determine whether this network is unneeded and should be lingered.
285 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
286 }
287
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700288 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700289 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700290 * from one net to another. Clear happens when we get a new
291 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
292 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700295
Robert Greenwalt434203a2010-10-11 16:00:27 -0700296 /**
297 * used internally to reload global proxy settings
298 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700299 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700300
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700301 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400302 * PAC manager has received new port.
303 */
304 private static final int EVENT_PROXY_HAS_CHANGED = 16;
305
Robert Greenwalte049c232014-04-11 15:53:27 -0700306 /**
307 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700308 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700309 */
310 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
311
Robert Greenwalt7b816022014-04-18 15:25:25 -0700312 /**
313 * used internally when registering NetworkAgents
314 * obj = Messenger
315 */
316 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
317
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 /**
319 * used to add a network request
320 * includes a NetworkRequestInfo
321 */
322 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
323
324 /**
325 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900326 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700327 * cancel it.
328 * includes a NetworkRequestInfo
329 */
330 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
331
332 /**
333 * used to add a network listener - no request
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
337
338 /**
339 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400340 * arg1 = UID of caller
341 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700342 */
343 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
344
Robert Greenwalta67be032014-05-16 15:49:14 -0700345 /**
346 * used internally when registering NetworkFactories
347 * obj = Messenger
348 */
349 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
350
Robert Greenwalt27711812014-06-25 16:45:57 -0700351 /**
352 * used internally to expire a wakelock when transitioning
353 * from one net to another. Expire happens when we fail to find
354 * a new network (typically after 1 minute) -
355 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
356 * a replacement network.
357 */
358 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
359
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700360 /**
361 * Used internally to indicate the system is ready.
362 */
363 private static final int EVENT_SYSTEM_READY = 25;
364
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800365 /**
366 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400367 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800368 */
369 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
370
371 /**
372 * used to remove a pending intent and its associated network request.
373 * arg1 = UID of caller
374 * obj = PendingIntent
375 */
376 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
377
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900378 /**
379 * used to specify whether a network should be used even if unvalidated.
380 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
381 * arg2 = whether to remember this choice in the future (1 or 0)
382 * obj = network
383 */
384 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
385
386 /**
387 * used to ask the user to confirm a connection to an unvalidated network.
388 * obj = network
389 */
390 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 /**
393 * used internally to (re)configure mobile data always-on settings.
394 */
395 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
396
Paul Jensen694f2b82015-06-17 14:15:39 -0400397 /**
398 * used to add a network listener with a pending intent
399 * obj = NetworkRequestInfo
400 */
401 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
402
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900403 /**
404 * used to specify whether a network should not be penalized when it becomes unvalidated.
405 */
406 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
407
408 /**
409 * used to trigger revalidation of a network.
410 */
411 private static final int EVENT_REVALIDATE_NETWORK = 36;
412
Erik Klinea24d4592018-01-11 21:07:29 +0900413 // Handle changes in Private DNS settings.
414 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
415
dalyk7301aa42018-03-05 12:42:22 -0500416 // Handle private DNS validation status updates.
417 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
418
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900419 private static String eventName(int what) {
420 return sMagicDecoderRing.get(what, Integer.toString(what));
421 }
422
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900423 /** Handler thread used for both of the handlers below. */
424 @VisibleForTesting
425 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700426 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700427 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700428 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700429 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900430 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700431
Mike Lockwood0f79b542009-08-14 14:18:49 -0400432 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800433 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400434
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700435 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700436 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800437 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700438
Chalard Jean52c2aa72018-06-07 16:44:04 +0900439 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
440 // the world when it changes.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900441 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400442
Erik Klineda4bfa82015-04-30 12:58:40 +0900443 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700444
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400445 private UserManager mUserManager;
446
Chalard Jean4133a122018-06-04 13:33:12 +0900447 private NetworkConfig[] mNetConfigs;
448 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700449
Robert Greenwalt50393202011-06-21 17:26:14 -0700450 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900451 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700452
Chalard Jean4133a122018-06-04 13:33:12 +0900453 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400454
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900455 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900456 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900457 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900458
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700459 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800460 private static final int MIN_NET_ID = 100; // some reserved marks
461 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700462 private int mNextNetId = MIN_NET_ID;
463
Robert Greenwalt34524f02014-05-18 16:22:10 -0700464 // sequence number of NetworkRequests
465 private int mNextNetworkRequestId = 1;
466
Erik Kline7523eb32015-07-09 18:24:03 +0900467 // NetworkRequest activity String log entries.
468 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
469 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
470
Hugo Benichic2ae2872016-07-11 11:05:12 +0900471 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900472 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900473 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
474
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900475 private static final int MAX_WAKELOCK_LOGS = 20;
476 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900477 private int mTotalWakelockAcquisitions = 0;
478 private int mTotalWakelockReleases = 0;
479 private long mTotalWakelockDurationMs = 0;
480 private long mMaxWakelockDurationMs = 0;
481 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900482
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
484 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400485 private static class ValidationLog {
486 final Network mNetwork;
Chalard Jeand771aa02018-04-26 16:16:10 +0900487 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489
Chalard Jeand771aa02018-04-26 16:16:10 +0900490 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 mNetwork = network;
Chalard Jeand771aa02018-04-26 16:16:10 +0900492 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400493 mLog = log;
494 }
495 }
Chalard Jean4133a122018-06-04 13:33:12 +0900496 private final ArrayDeque<ValidationLog> mValidationLogs = new ArrayDeque<>(MAX_VALIDATION_LOGS);
Paul Jensen0808eb82016-06-03 13:51:21 -0400497
Chalard Jeand771aa02018-04-26 16:16:10 +0900498 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900499 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700500 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
501 mValidationLogs.removeLast();
502 }
Chalard Jeand771aa02018-04-26 16:16:10 +0900503 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700504 }
505 }
506
Hugo Benichif9fdf872016-07-28 17:53:06 +0900507 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900508
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700509 @GuardedBy("mBandwidthRequests")
510 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
511
Erik Kline065ab6e2016-10-02 18:02:14 +0900512 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900513 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900514
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900515 @VisibleForTesting
516 final MultipathPolicyTracker mMultipathPolicyTracker;
517
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 /**
519 * Implements support for the legacy "one network per network type" model.
520 *
521 * We used to have a static array of NetworkStateTrackers, one for each
522 * network type, but that doesn't work any more now that we can have,
523 * for example, more that one wifi network. This class stores all the
524 * NetworkAgentInfo objects that support a given type, but the legacy
525 * API will only see the first one.
526 *
527 * It serves two main purposes:
528 *
529 * 1. Provide information about "the network for a given type" (since this
530 * API only supports one).
531 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
532 * the first network for a given type changes, or if the default network
533 * changes.
534 */
535 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900537 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900539
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540 /**
541 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
542 * Each list holds references to all NetworkAgentInfos that are used to
543 * satisfy requests for that network type.
544 *
545 * This array is built out at startup such that an unsupported network
546 * doesn't get an ArrayList instance, making this a tristate:
547 * unsupported, supported but not active and active.
548 *
549 * The actual lists are populated when we scan the network types that
550 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900551 *
552 * Threading model:
553 * - addSupportedType() is only called in the constructor
554 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
555 * They are therefore not thread-safe with respect to each other.
556 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
557 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
558 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561
562 public LegacyTypeTracker() {
563 mTypeLists = (ArrayList<NetworkAgentInfo>[])
564 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
565 }
566
567 public void addSupportedType(int type) {
568 if (mTypeLists[type] != null) {
569 throw new IllegalStateException(
570 "legacy list for type " + type + "already initialized");
571 }
Chalard Jean4133a122018-06-04 13:33:12 +0900572 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 }
574
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public boolean isTypeSupported(int type) {
576 return isNetworkTypeValid(type) && mTypeLists[type] != null;
577 }
578
579 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900580 synchronized (mTypeLists) {
581 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
582 return mTypeLists[type].get(0);
583 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
587
Robert Greenwalt8d482522015-06-24 13:23:42 -0700588 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900589 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 }
595 }
596
597 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 public void add(int type, NetworkAgentInfo nai) {
599 if (!isTypeSupported(type)) {
600 return; // Invalid network type.
601 }
602 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
603
604 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
605 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700606 return;
607 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 synchronized (mTypeLists) {
609 list.add(nai);
610 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900611
612 // 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 +0900613 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
616 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 }
619
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
623 if (list == null || list.isEmpty()) {
624 return;
625 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627
Hugo Benichi78caa2582016-06-21 09:48:07 +0900628 synchronized (mTypeLists) {
629 if (!list.remove(nai)) {
630 return;
631 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 final DetailedState state = DetailedState.DISCONNECTED;
635
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 maybeLogBroadcast(nai, state, type, wasDefault);
638 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639 }
640
641 if (!list.isEmpty() && wasFirstNetwork) {
642 if (DBG) log("Other network available for type " + type +
643 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
646 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900647 }
648 }
649
650 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900651 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
652 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700653 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900654 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 }
656 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700657
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 // send out another legacy broadcast - currently only used for suspend/unsuspend
659 // toggle
660 public void update(NetworkAgentInfo nai) {
661 final boolean isDefault = isDefaultNetwork(nai);
662 final DetailedState state = nai.networkInfo.getDetailedState();
663 for (int type = 0; type < mTypeLists.length; type++) {
664 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700665 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900666 final boolean isFirst = contains && (nai == list.get(0));
667 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700668 maybeLogBroadcast(nai, state, type, isDefault);
669 sendLegacyNetworkBroadcast(nai, state, type);
670 }
671 }
672 }
673
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900675 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 String state = (nai.networkInfo != null) ?
677 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
678 "???/???";
679 return name + " " + state;
680 }
681
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 pw.println("mLegacyTypeTracker:");
684 pw.increaseIndent();
685 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900689 pw.println();
690 pw.println("Current state:");
691 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900692 synchronized (mTypeLists) {
693 for (int type = 0; type < mTypeLists.length; type++) {
694 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
695 for (NetworkAgentInfo nai : mTypeLists[type]) {
696 pw.println(type + " " + naiToString(nai));
697 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900698 }
699 }
700 pw.decreaseIndent();
701 pw.decreaseIndent();
702 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700703 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700704 }
705 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
706
Vishnu Nair5c010902017-10-26 10:08:50 -0700707 /**
708 * Helper class which parses out priority arguments and dumps sections according to their
709 * priority. If priority arguments are omitted, function calls the legacy dump command.
710 */
711 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
712 @Override
713 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
714 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
715 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
716 }
717
718 @Override
719 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
720 doDump(fd, pw, args, asProto);
721 }
722
723 @Override
724 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
725 doDump(fd, pw, args, asProto);
726 }
727 };
728
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700730 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900731 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
732 }
733
734 @VisibleForTesting
735 protected ConnectivityService(Context context, INetworkManagementService netManager,
736 INetworkStatsService statsService, INetworkPolicyManager policyManager,
737 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800738 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800739
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900740 mSystemProperties = getSystemProperties();
741
Hugo Benichif9fdf872016-07-28 17:53:06 +0900742 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900743 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900744 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900745 mNetworkRequests.put(mDefaultRequest, defaultNRI);
746 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900747
Chalard Jeandda156a2018-01-10 21:19:32 +0900748 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900749 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700750
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900751 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900752 mHandlerThread.start();
753 mHandler = new InternalHandler(mHandlerThread.getLooper());
754 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700755
Jeremy Joslin79294842014-12-03 17:15:28 -0800756 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
757 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
758
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900759 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900760
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700761 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700762 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800763 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700764 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900765 mPolicyManagerInternal = checkNotNull(
766 LocalServices.getService(NetworkPolicyManagerInternal.class),
767 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900768 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900769
Jeff Sharkey82f85212012-08-24 11:17:25 -0700770 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700771 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900774 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700775 } catch (RemoteException e) {
776 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700777 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700778 }
779
780 final PowerManager powerManager = (PowerManager) context.getSystemService(
781 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700782 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
783 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
784 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800785 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700786
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700787 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700788
Wink Saville51f456f2013-04-23 14:26:51 -0700789 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900790 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700791 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792 String[] naStrings = context.getResources().getStringArray(
793 com.android.internal.R.array.networkAttributes);
794 for (String naString : naStrings) {
795 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700796 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700797 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700798 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800799 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700800 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700801 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700802 }
Wink Saville51f456f2013-04-23 14:26:51 -0700803 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
804 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
805 n.type);
806 continue;
807 }
Wink Saville975c8482011-04-07 14:23:45 -0700808 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800809 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700810 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700811 continue;
812 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700813 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700814
Wink Saville975c8482011-04-07 14:23:45 -0700815 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700816 mNetworksDefined++;
817 } catch(Exception e) {
818 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700819 }
820 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700821
822 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
823 if (mNetConfigs[TYPE_VPN] == null) {
824 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
825 // don't need to add TYPE_VPN to mNetConfigs.
826 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
827 mNetworksDefined++; // used only in the log() statement below.
828 }
829
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900830 // Do the same for Ethernet, since it's often not specified in the configs, although many
831 // devices can use it via USB host adapters.
832 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
833 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
834 mNetworksDefined++;
835 }
836
Wink Saville5e56bc52013-07-29 15:00:57 -0700837 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700838
Robert Greenwalt50393202011-06-21 17:26:14 -0700839 mProtectedNetworks = new ArrayList<Integer>();
840 int[] protectedNetworks = context.getResources().getIntArray(
841 com.android.internal.R.array.config_protectedNetworks);
842 for (int p : protectedNetworks) {
843 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
844 mProtectedNetworks.add(p);
845 } else {
846 if (DBG) loge("Ignoring protectedNetwork " + p);
847 }
848 }
849
Erik Kline47222fc2017-04-30 19:36:15 +0900850 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800851
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700852 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
853
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700854 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700855 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100856 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700857 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700858 intentFilter.addAction(Intent.ACTION_USER_ADDED);
859 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000860 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700861 mContext.registerReceiverAsUser(
862 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000863 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
864 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900865
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700866 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700867 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700868 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700869 } catch (RemoteException e) {
870 loge("Error registering observer :" + e);
871 }
872
Erik Klineda4bfa82015-04-30 12:58:40 +0900873 mSettingsObserver = new SettingsObserver(mContext, mHandler);
874 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800875
Chalard Jean4133a122018-06-04 13:33:12 +0900876 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
877 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400878
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400879 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900880
881 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900882 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
883 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900884
885 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
886 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
887 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
888 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
889 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
890 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
891 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900892
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900893 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900894 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900895 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900896
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900897 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
898
Erik Kline1742fe12017-12-13 19:40:49 +0900899 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900900 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700902
Erik Kline47222fc2017-04-30 19:36:15 +0900903 private Tethering makeTethering() {
904 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900905 final TetheringDependencies deps = new TetheringDependencies() {
906 @Override
907 public boolean isTetheringSupported() {
908 return ConnectivityService.this.isTetheringSupported();
909 }
Erik Kline72302902018-06-14 17:36:40 +0900910 @Override
911 public NetworkRequest getDefaultNetworkRequest() {
912 return mDefaultRequest;
913 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900914 };
Erik Kline47222fc2017-04-30 19:36:15 +0900915 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
916 IoThread.get().getLooper(), new MockableSystemProperties(),
917 deps);
918 }
919
Chalard Jean26400492018-04-18 20:18:38 +0900920 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
921 final NetworkCapabilities netCap = new NetworkCapabilities();
922 netCap.addCapability(NET_CAPABILITY_INTERNET);
923 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
924 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
925 netCap.setSingleUid(uid);
926 return netCap;
927 }
928
Chalard Jeandda156a2018-01-10 21:19:32 +0900929 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900930 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900931 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900932 netCap.addCapability(NET_CAPABILITY_INTERNET);
933 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900934 if (transportType > -1) {
935 netCap.addTransportType(transportType);
936 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900937 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900938 }
939
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900940 // Used only for testing.
941 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700942 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900943 // changing ContentResolver to make registerContentObserver non-final).
944 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
945 // by subclassing SettingsObserver.
946 @VisibleForTesting
947 void updateMobileDataAlwaysOn() {
948 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
949 }
950
Erik Kline736353a2018-03-21 07:18:33 -0700951 // See FakeSettingsProvider comment above.
952 @VisibleForTesting
953 void updatePrivateDnsSettings() {
954 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
955 }
956
Erik Klineda4bfa82015-04-30 12:58:40 +0900957 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900958 final boolean enable = toBool(Settings.Global.getInt(
959 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900960 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
961 if (enable == isEnabled) {
962 return; // Nothing to do.
963 }
964
965 if (enable) {
966 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900967 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900968 } else {
969 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
970 }
971 }
972
973 private void registerSettingsCallbacks() {
974 // Watch for global HTTP proxy changes.
975 mSettingsObserver.observe(
976 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
977 EVENT_APPLY_GLOBAL_HTTP_PROXY);
978
979 // Watch for whether or not to keep mobile data always on.
980 mSettingsObserver.observe(
981 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
982 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
983 }
984
Erik Klinea24d4592018-01-11 21:07:29 +0900985 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700986 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
987 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900988 }
989 }
990
Robert Greenwalt34524f02014-05-18 16:22:10 -0700991 private synchronized int nextNetworkRequestId() {
992 return mNextNetworkRequestId++;
993 }
994
Paul Jensen67b0b072015-06-10 11:22:17 -0400995 @VisibleForTesting
996 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400997 synchronized (mNetworkForNetId) {
998 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
999 int netId = mNextNetId;
1000 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1001 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001002 if (!mNetIdInUse.get(netId)) {
1003 mNetIdInUse.put(netId, true);
1004 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001005 }
1006 }
1007 }
1008 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001009 }
1010
Chalard Jeanc0982912018-06-07 16:11:34 +09001011 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001013 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1014 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 state = nai.getNetworkState();
1017 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 final NetworkInfo info = new NetworkInfo(networkType, 0,
1020 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1022 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001023 final NetworkCapabilities capabilities = new NetworkCapabilities();
1024 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1025 !info.isRoaming());
1026 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001029 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 return state;
1031 } else {
1032 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001034 }
1035
junyulai4a192e22018-06-13 15:00:37 +08001036 @VisibleForTesting
1037 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 if (network == null) {
1039 return null;
1040 }
Erik Kline736353a2018-03-21 07:18:33 -07001041 return getNetworkAgentInfoForNetId(network.netId);
1042 }
1043
1044 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001045 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001046 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001050 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001051 synchronized (mVpns) {
1052 if (!mLockdownEnabled) {
1053 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001054 Vpn vpn = mVpns.get(user);
1055 if (vpn != null && vpn.appliesToUid(uid)) {
1056 return vpn.getUnderlyingNetworks();
1057 }
1058 }
1059 }
1060 return null;
1061 }
1062
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001064 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001065
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001066 final Network[] networks = getVpnUnderlyingNetworks(uid);
1067 if (networks != null) {
1068 // getUnderlyingNetworks() returns:
1069 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1070 // empty array => the VPN explicitly said "no default network".
1071 // non-empty array => the VPN specified one or more default networks; we use the
1072 // first one.
1073 if (networks.length > 0) {
1074 nai = getNetworkAgentInfoForNetwork(networks[0]);
1075 } else {
1076 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001077 }
1078 }
1079
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 return nai.getNetworkState();
1082 } else {
1083 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001085 }
1086
1087 /**
1088 * Check if UID should be blocked from using the network with the given LinkProperties.
1089 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1091 boolean ignoreBlocked) {
1092 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001093 if (ignoreBlocked) {
1094 return false;
1095 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001097 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1098 if (isSystem(uid)) {
1099 return false;
1100 }
Robin Lee17e61832016-05-09 13:46:28 +01001101 synchronized (mVpns) {
1102 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1103 if (vpn != null && vpn.isBlockingUid(uid)) {
1104 return true;
1105 }
1106 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001107 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001108 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 }
1110
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001111 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001112 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1113 return;
1114 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001115 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001116 synchronized (mBlockedAppUids) {
1117 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001118 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001119 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001120 blocked = false;
1121 } else {
1122 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001123 }
1124 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001125 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1126 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1127 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001128 }
1129
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001131 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1132 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001133 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1137
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001139 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 }
Hugo Benichi69744342017-11-27 10:57:16 +09001141 synchronized (mVpns) {
1142 if (mLockdownTracker != null) {
1143 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1144 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001145 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 }
1147
1148 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 * Return NetworkInfo for the active (i.e., connected) network interface.
1150 * It is assumed that at most one network is active at a time. If more
1151 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001152 * @return the info for the active network, or {@code null} if none is
1153 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 enforceAccessPermission();
1158 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001160 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1162 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164
Paul Jensen31a94f42015-02-13 14:18:39 -05001165 @Override
1166 public Network getActiveNetwork() {
1167 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001169 }
1170
1171 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001173 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001175 }
1176
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001178 final int user = UserHandle.getUserId(uid);
1179 int vpnNetId = NETID_UNSET;
1180 synchronized (mVpns) {
1181 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001182 // TODO : now that capabilities contain the UID, the appliesToUid test should
1183 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001184 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1185 }
1186 NetworkAgentInfo nai;
1187 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001188 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001189 if (nai != null) {
1190 final NetworkCapabilities requiredCaps =
1191 createDefaultNetworkCapabilitiesForUid(uid);
1192 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1193 return nai.network;
1194 }
1195 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 }
1197 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 if (nai != null
1199 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1200 nai = null;
1201 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001202 return nai != null ? nai.network : null;
1203 }
1204
Lorenzo Colitti18660282016-07-04 12:55:44 +09001205 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001206 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1207 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 final int uid = Binder.getCallingUid();
1209 NetworkState state = getUnfilteredActiveNetworkState(uid);
1210 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001211 }
1212
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001214 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001215 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001216 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001217 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001218 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001219 }
1220
1221 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 public NetworkInfo getNetworkInfo(int networkType) {
1223 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001224 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001225 if (getVpnUnderlyingNetworks(uid) != null) {
1226 // A VPN is active, so we may need to return one of its underlying networks. This
1227 // information is not available in LegacyTypeTracker, so we have to get it from
1228 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001229 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001230 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001231 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001232 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001233 }
1234 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001235 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001240 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001242 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001244 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001245 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001246 return state.networkInfo;
1247 } else {
1248 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001249 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001250 }
1251
1252 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 public NetworkInfo[] getAllNetworkInfo() {
1254 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001255 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001256 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1257 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 NetworkInfo info = getNetworkInfo(networkType);
1259 if (info != null) {
1260 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001263 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001266 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001267 public Network getNetworkForType(int networkType) {
1268 enforceAccessPermission();
1269 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001270 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001271 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001272 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001273 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001274 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001275 }
1276
1277 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 public Network[] getAllNetworks() {
1279 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001281 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001283 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001284 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001285 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001287 }
1288
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001289 @Override
1290 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1291 // The basic principle is: if an app's traffic could possibly go over a
1292 // network, without the app doing anything multinetwork-specific,
1293 // (hence, by "default"), then include that network's capabilities in
1294 // the array.
1295 //
1296 // In the normal case, app traffic only goes over the system's default
1297 // network connection, so that's the only network returned.
1298 //
1299 // With a VPN in force, some app traffic may go into the VPN, and thus
1300 // over whatever underlying networks the VPN specifies, while other app
1301 // traffic may go over the system default network (e.g.: a split-tunnel
1302 // VPN, or an app disallowed by the VPN), so the set of networks
1303 // returned includes the VPN's underlying networks and the system
1304 // default.
1305 enforceAccessPermission();
1306
Chalard Jean4133a122018-06-04 13:33:12 +09001307 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001308
1309 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001310 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001311 if (nc != null) {
1312 result.put(nai.network, nc);
1313 }
1314
Hugo Benichi69744342017-11-27 10:57:16 +09001315 synchronized (mVpns) {
1316 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001317 Vpn vpn = mVpns.get(userId);
1318 if (vpn != null) {
1319 Network[] networks = vpn.getUnderlyingNetworks();
1320 if (networks != null) {
1321 for (Network network : networks) {
1322 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001323 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001324 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001325 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001326 }
1327 }
1328 }
1329 }
1330 }
1331 }
1332
1333 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1334 out = result.values().toArray(out);
1335 return out;
1336 }
1337
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001339 public boolean isNetworkSupported(int networkType) {
1340 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001342 }
1343
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001344 /**
1345 * Return LinkProperties for the active (i.e., connected) default
1346 * network interface. It is assumed that at most one default network
1347 * is active at a time. If more than one is active, it is indeterminate
1348 * which will be returned.
1349 * @return the ip properties for the active network, or {@code null} if
1350 * none is active
1351 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001352 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001353 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 enforceAccessPermission();
1355 final int uid = Binder.getCallingUid();
1356 NetworkState state = getUnfilteredActiveNetworkState(uid);
1357 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001358 }
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001361 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001363 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1364 if (nai != null) {
1365 synchronized (nai) {
1366 return new LinkProperties(nai.linkProperties);
1367 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001368 }
1369 return null;
1370 }
1371
Robert Greenwalt12e67352014-05-13 21:41:06 -07001372 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001373 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001374 public LinkProperties getLinkProperties(Network network) {
1375 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001376 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1377 }
1378
1379 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1380 if (nai == null) {
1381 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001382 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001383 synchronized (nai) {
1384 return new LinkProperties(nai.linkProperties);
1385 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001386 }
1387
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001388 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001389 if (nai != null) {
1390 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001391 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001392 return networkCapabilitiesRestrictedForCallerPermissions(
1393 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001394 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001395 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001396 }
1397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001398 return null;
1399 }
1400
1401 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001402 public NetworkCapabilities getNetworkCapabilities(Network network) {
1403 enforceAccessPermission();
1404 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1405 }
1406
Chalard Jeanb03a6222018-04-11 21:09:10 +09001407 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001408 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001409 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001410 if (!checkSettingsPermission(callerPid, callerUid)) {
1411 newNc.setUids(null);
1412 newNc.setSSID(null);
1413 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001414 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001415 }
1416
Chalard Jeanb552c462018-02-21 18:43:54 +09001417 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1418 if (!checkSettingsPermission()) {
1419 nc.setSingleUid(Binder.getCallingUid());
1420 }
1421 }
1422
Chalard Jean26aa91a2018-03-20 19:13:57 +09001423 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1424 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1425 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1426 }
1427 }
1428
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001429 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001430 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001431 // Require internal since we're handing out IMSI details
1432 enforceConnectivityInternalPermission();
1433
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001434 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001435 for (Network network : getAllNetworks()) {
1436 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1437 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001438 // TODO (b/73321673) : NetworkState contains a copy of the
1439 // NetworkCapabilities, which may contain UIDs of apps to which the
1440 // network applies. Should the UIDs be cleared so as not to leak or
1441 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001442 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001443 }
1444 }
1445 return result.toArray(new NetworkState[result.size()]);
1446 }
1447
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001448 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001449 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001450 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001451 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1452 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1453 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001454 }
1455
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001456 @Override
1457 public boolean isActiveNetworkMetered() {
1458 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001459
Eric Enslenc81ef192018-02-07 18:03:53 -08001460 final int uid = Binder.getCallingUid();
1461 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001462 if (caps != null) {
1463 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1464 } else {
1465 // Always return the most conservative value
1466 return true;
1467 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001468 }
1469
Jeff Sharkey216c1812012-08-05 14:29:23 -07001470 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1471 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001472 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001473 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001474 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001475 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001476 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001477
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001478 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 * Ensure that a network route exists to deliver traffic to the specified
1480 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001481 * @param networkType the type of the network over which traffic to the
1482 * specified host is to be routed
1483 * @param hostAddress the IP address of the host to which the route is
1484 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 * @return {@code true} on success, {@code false} on failure
1486 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001487 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001488 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001490 if (mProtectedNetworks.contains(networkType)) {
1491 enforceConnectivityInternalPermission();
1492 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001493
Chad Brubakerc0234532014-02-14 13:24:29 -08001494 InetAddress addr;
1495 try {
1496 addr = InetAddress.getByAddress(hostAddress);
1497 } catch (UnknownHostException e) {
1498 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1499 return false;
1500 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001503 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 return false;
1505 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001506
1507 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1508 if (nai == null) {
1509 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1510 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1511 } else {
1512 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1513 }
1514 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001515 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001516
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001517 DetailedState netState;
1518 synchronized (nai) {
1519 netState = nai.networkInfo.getDetailedState();
1520 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001521
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001522 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001523 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001524 log("requestRouteToHostAddress on down network "
1525 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001526 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001527 }
1528 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001530
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001531 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001532 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001533 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001534 LinkProperties lp;
1535 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001536 synchronized (nai) {
1537 lp = nai.linkProperties;
1538 netId = nai.network.netId;
1539 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001540 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001541 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1542 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001543 } finally {
1544 Binder.restoreCallingIdentity(token);
1545 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001546 }
1547
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001548 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001549 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001550 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001551 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001552 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001553 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001554 if (bestRoute.getGateway().equals(addr)) {
1555 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001556 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001557 } else {
1558 // if we will connect to this through another route, add a direct route
1559 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001560 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001561 }
1562 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001563 if (DBG) log("Adding legacy route " + bestRoute +
1564 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001565 try {
1566 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1567 } catch (Exception e) {
1568 // never crash - catch them all
1569 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001570 return false;
1571 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001572 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
dalyk7301aa42018-03-05 12:42:22 -05001575 @VisibleForTesting
1576 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1577 @Override
1578 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1579 String hostname, boolean validated) {
1580 try {
1581 mHandler.sendMessage(mHandler.obtainMessage(
1582 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1583 new PrivateDnsValidationUpdate(netId,
1584 InetAddress.parseNumericAddress(ipAddress),
1585 hostname, validated)));
1586 } catch (IllegalArgumentException e) {
1587 loge("Error parsing ip address in validation event");
1588 }
1589 }
1590 };
1591
1592 @VisibleForTesting
1593 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001594 final IIpConnectivityMetrics ipConnectivityMetrics =
1595 IIpConnectivityMetrics.Stub.asInterface(
1596 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1597 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001598 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001599 return;
dalyk7301aa42018-03-05 12:42:22 -05001600 }
1601
1602 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001603 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001604 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1605 mNetdEventCallback);
1606 } catch (Exception e) {
1607 loge("Error registering netd callback: " + e);
1608 }
1609 }
1610
Jeff Sharkey75d31892018-01-18 22:01:59 +09001611 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001612 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001613 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001614 // TODO: notify UID when it has requested targeted updates
1615 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001616 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001617 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001618 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001619 if (restrictBackground) {
1620 log("onRestrictBackgroundChanged(true): disabling tethering");
1621 mTethering.untetherAll();
1622 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001623 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001624 };
1625
Robin Lee3b3dd942015-05-12 18:14:58 +01001626 /**
1627 * Require that the caller is either in the same user or has appropriate permission to interact
1628 * across users.
1629 *
1630 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1631 */
1632 private void enforceCrossUserPermission(int userId) {
1633 if (userId == UserHandle.getCallingUserId()) {
1634 // Not a cross-user call.
1635 return;
1636 }
1637 mContext.enforceCallingOrSelfPermission(
1638 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1639 "ConnectivityService");
1640 }
1641
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001642 private void enforceInternetPermission() {
1643 mContext.enforceCallingOrSelfPermission(
1644 android.Manifest.permission.INTERNET,
1645 "ConnectivityService");
1646 }
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001649 mContext.enforceCallingOrSelfPermission(
1650 android.Manifest.permission.ACCESS_NETWORK_STATE,
1651 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653
1654 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001655 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
Charles He36738632017-05-15 17:07:18 +01001658 private void enforceSettingsPermission() {
1659 mContext.enforceCallingOrSelfPermission(
1660 android.Manifest.permission.NETWORK_SETTINGS,
1661 "ConnectivityService");
1662 }
1663
Chalard Jeanb552c462018-02-21 18:43:54 +09001664 private boolean checkSettingsPermission() {
1665 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1666 android.Manifest.permission.NETWORK_SETTINGS);
1667 }
1668
1669 private boolean checkSettingsPermission(int pid, int uid) {
1670 return PERMISSION_GRANTED == mContext.checkPermission(
1671 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1672 }
1673
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001674 private void enforceTetherAccessPermission() {
1675 mContext.enforceCallingOrSelfPermission(
1676 android.Manifest.permission.ACCESS_NETWORK_STATE,
1677 "ConnectivityService");
1678 }
1679
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001680 private void enforceConnectivityInternalPermission() {
1681 mContext.enforceCallingOrSelfPermission(
1682 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1683 "ConnectivityService");
1684 }
1685
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001686 private boolean checkNetworkStackPermission() {
1687 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1688 android.Manifest.permission.NETWORK_STACK);
1689 }
1690
Hugo Benichi514da602016-07-19 15:59:27 +09001691 private void enforceConnectivityRestrictedNetworksPermission() {
1692 try {
1693 mContext.enforceCallingOrSelfPermission(
1694 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1695 "ConnectivityService");
1696 return;
1697 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1698 enforceConnectivityInternalPermission();
1699 }
1700
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001701 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001702 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001703 }
1704
Lorenzo Colitti18660282016-07-04 12:55:44 +09001705 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001706 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001707 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001708 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001709 }
1710
1711 private void sendInetConditionBroadcast(NetworkInfo info) {
1712 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1713 }
1714
Wink Saville628b0852011-08-04 15:01:58 -07001715 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001716 synchronized (mVpns) {
1717 if (mLockdownTracker != null) {
1718 info = new NetworkInfo(info);
1719 mLockdownTracker.augmentNetworkInfo(info);
1720 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001721 }
1722
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001723 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001724 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001725 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (info.isFailover()) {
1727 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1728 info.setFailover(false);
1729 }
1730 if (info.getReason() != null) {
1731 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1732 }
1733 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001734 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1735 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001737 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001738 return intent;
1739 }
1740
1741 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1742 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1743 }
1744
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001745 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001746 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1747 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1748 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001749 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001750 final long ident = Binder.clearCallingIdentity();
1751 try {
1752 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1753 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001757 }
1758
Mike Lockwood0f79b542009-08-14 14:18:49 -04001759 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001760 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001761 if (!mSystemReady) {
1762 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001763 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001764 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001765 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001766 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001767 }
1768
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001769 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001770 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001771 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001772 final NetworkInfo ni = intent.getParcelableExtra(
1773 ConnectivityManager.EXTRA_NETWORK_INFO);
1774 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1775 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1776 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001777 } else {
1778 BroadcastOptions opts = BroadcastOptions.makeBasic();
1779 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1780 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001781 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001782 final IBatteryStats bs = BatteryStatsService.getService();
1783 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001784 bs.noteConnectivityChanged(intent.getIntExtra(
1785 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001786 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001787 } catch (RemoteException e) {
1788 }
Chad Brubakerac925012018-03-08 10:37:09 -08001789 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001790 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001791 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001792 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001793 } finally {
1794 Binder.restoreCallingIdentity(ident);
1795 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001796 }
1797 }
1798
1799 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001800 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001801 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001802
Hugo Benichi20035e02017-04-26 14:53:28 +09001803 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001804 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001805 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001806 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001807 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001808 }
1809 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001810 // load the global proxy at startup
1811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001812
Robin Lee244ce8e2016-01-05 18:03:46 +00001813 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1814 // for user to unlock device too.
1815 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001816
Erik Klineda4bfa82015-04-30 12:58:40 +09001817 // Configure whether mobile data is always on.
1818 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1819
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001821
1822 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001827 *
1828 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001829 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001830 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001831 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1832 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001833
1834 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001836
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 if (networkAgent.networkCapabilities.hasTransport(
1838 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001839 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1840 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001841 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001842 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001843 } else if (networkAgent.networkCapabilities.hasTransport(
1844 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001845 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1846 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001847 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001848 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001849 } else {
1850 // do not track any other networks
1851 timeout = 0;
1852 }
1853
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001855 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001856 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001857 } catch (Exception e) {
1858 // You shall not crash!
1859 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001860 }
1861 }
1862 }
1863
1864 /**
1865 * Remove data activity tracking when network disconnects.
1866 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001867 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1868 final String iface = networkAgent.linkProperties.getInterfaceName();
1869 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001870
Robert Greenwalt7b816022014-04-18 15:25:25 -07001871 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1872 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001873 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001874 // the call fails silently if no idle timer setup for this interface
Haoyu Bai04124232012-06-28 15:26:19 -07001875 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001876 } catch (Exception e) {
1877 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001878 }
1879 }
1880 }
1881
1882 /**
Chalard Jean4d660112018-06-04 16:52:49 +09001883 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09001884 * and set it on it's iface.
1885 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001886 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1887 final String iface = newLp.getInterfaceName();
1888 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001889 if (oldLp == null && mtu == 0) {
1890 // Silently ignore unset MTU value.
1891 return;
1892 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1894 if (VDBG) log("identical MTU - not setting");
1895 return;
1896 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001897 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001898 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001899 return;
1900 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001901
w1997615afd812014-08-05 15:18:11 -07001902 // Cannot set MTU without interface name
1903 if (TextUtils.isEmpty(iface)) {
1904 loge("Setting MTU size with null iface.");
1905 return;
1906 }
1907
Robert Greenwalt7b816022014-04-18 15:25:25 -07001908 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001909 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001910 mNetd.setMtu(iface, mtu);
1911 } catch (Exception e) {
1912 Slog.e(TAG, "exception in setMtu()" + e);
1913 }
1914 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001915
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001916 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001917 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1918
1919 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001920 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001921 protected MockableSystemProperties getSystemProperties() {
1922 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001923 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001924
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001925 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1926 if (isDefaultNetwork(nai) == false) {
1927 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001928 }
1929
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001930 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1931 String[] values = null;
1932 if (tcpBufferSizes != null) {
1933 values = tcpBufferSizes.split(",");
1934 }
1935
1936 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001937 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001938 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1939 values = tcpBufferSizes.split(",");
1940 }
1941
1942 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1943
1944 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001945 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001946
1947 final String prefix = "/sys/kernel/ipv4/tcp_";
1948 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1949 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1950 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1951 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1952 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1953 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1954 mCurrentTcpBufferSizes = tcpBufferSizes;
1955 } catch (IOException e) {
1956 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001957 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001958
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001959 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001960 Settings.Global.TCP_DEFAULT_INIT_RWND,
1961 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001962 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1963 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001964 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001965 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001966 }
1967
Robert Greenwalt562cc542014-05-15 18:07:26 -07001968 @Override
1969 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001970 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001971 NETWORK_RESTORE_DELAY_PROP_NAME);
1972 if(restoreDefaultNetworkDelayStr != null &&
1973 restoreDefaultNetworkDelayStr.length() != 0) {
1974 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001975 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001976 } catch (NumberFormatException e) {
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001979 // if the system property isn't set, use the value for the apn type
1980 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1981
1982 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1983 (mNetConfigs[networkType] != null)) {
1984 ret = mNetConfigs[networkType].restoreTime;
1985 }
1986 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001989 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1990 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1991 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09001992 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001993 // Start gathering diagnostic information.
1994 netDiags.add(new NetworkDiagnostics(
1995 nai.network,
1996 new LinkProperties(nai.linkProperties), // Must be a copy.
1997 DIAG_TIME_MS));
1998 }
1999
2000 for (NetworkDiagnostics netDiag : netDiags) {
2001 pw.println();
2002 netDiag.waitForMeasurements();
2003 netDiag.dump(pw);
2004 }
2005 }
2006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002008 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002009 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2010 }
2011
2012 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002013 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002014 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002015 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002016
Erik Kline3f8306b2018-05-01 16:51:44 +09002017 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002018 dumpNetworkDiagnostics(pw);
2019 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002020 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002021 mTethering.dump(fd, pw, args);
2022 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002023 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2024 dumpNetworks(pw);
2025 return;
2026 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2027 dumpNetworkRequests(pw);
2028 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002029 }
Erik Kline379747a2015-06-05 17:47:34 +09002030
Lorenzo Colittie3805462015-06-03 11:18:24 +09002031 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002032 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002033 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002034 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002035 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002036 pw.println();
2037
Paul Jensen85cf78e2015-06-25 13:25:07 -04002038 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002039 pw.print("Active default network: ");
2040 if (defaultNai == null) {
2041 pw.println("none");
2042 } else {
2043 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002045 pw.println();
2046
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002047 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002048 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002049 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002050 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002051 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002052
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002053 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002054 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002055 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002056 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002057 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002058
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002059 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002060
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002061 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002062 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002064 pw.println();
2065 mKeepaliveTracker.dump(pw);
2066
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002067 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002068 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002069
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002070 pw.println();
2071 mMultipathPolicyTracker.dump(pw);
2072
Erik Kline3f8306b2018-05-01 16:51:44 +09002073 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002074 pw.println();
2075 synchronized (mValidationLogs) {
2076 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002077 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002078 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002079 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002080 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002081 pw.decreaseIndent();
2082 }
2083 }
Erik Kline7523eb32015-07-09 18:24:03 +09002084
2085 pw.println();
2086 pw.println("mNetworkRequestInfoLogs (most recent first):");
2087 pw.increaseIndent();
2088 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2089 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002090
2091 pw.println();
2092 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2093 pw.increaseIndent();
2094 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2095 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002096
2097 pw.println();
2098 pw.println("NetTransition WakeLock activity (most recent first):");
2099 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002100 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2101 pw.println("total releases: " + mTotalWakelockReleases);
2102 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2103 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2104 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2105 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2106 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2107 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002108 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002109
2110 pw.println();
2111 pw.println("bandwidth update requests (by uid):");
2112 pw.increaseIndent();
2113 synchronized (mBandwidthRequests) {
2114 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2115 pw.println("[" + mBandwidthRequests.keyAt(i)
2116 + "]: " + mBandwidthRequests.valueAt(i));
2117 }
2118 }
2119 pw.decreaseIndent();
2120
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002121 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124
Hugo Benichi14683812018-09-03 08:32:56 +09002125 private void dumpNetworks(IndentingPrintWriter pw) {
2126 for (NetworkAgentInfo nai : networksSortedById()) {
2127 pw.println(nai.toString());
2128 pw.increaseIndent();
2129 pw.println(String.format(
2130 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2131 nai.numForegroundNetworkRequests(),
2132 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2133 nai.numBackgroundNetworkRequests(),
2134 nai.numNetworkRequests()));
2135 pw.increaseIndent();
2136 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2137 pw.println(nai.requestAt(i).toString());
2138 }
2139 pw.decreaseIndent();
2140 pw.println("Lingered:");
2141 pw.increaseIndent();
2142 nai.dumpLingerTimers(pw);
2143 pw.decreaseIndent();
2144 pw.decreaseIndent();
2145 }
2146 }
2147
2148 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2149 for (NetworkRequestInfo nri : requestsSortedById()) {
2150 pw.println(nri.toString());
2151 }
2152 }
2153
Hugo Benichia2a917c2018-09-03 08:19:02 +09002154 /**
2155 * Return an array of all current NetworkAgentInfos sorted by network id.
2156 */
2157 private NetworkAgentInfo[] networksSortedById() {
2158 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2159 networks = mNetworkAgentInfos.values().toArray(networks);
2160 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2161 return networks;
2162 }
2163
2164 /**
2165 * Return an array of all current NetworkRequest sorted by request id.
2166 */
2167 private NetworkRequestInfo[] requestsSortedById() {
2168 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2169 requests = mNetworkRequests.values().toArray(requests);
2170 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2171 return requests;
2172 }
2173
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002174 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002175 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002176 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002177 if (officialNai != null && officialNai.equals(nai)) return true;
2178 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002179 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002180 " - " + nai);
2181 }
2182 return false;
2183 }
2184
Robert Greenwalt42acef32009-08-12 16:08:25 -07002185 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002186 private class NetworkStateTrackerHandler extends Handler {
2187 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002188 super(looper);
2189 }
2190
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002191 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002193 default:
2194 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002195 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002196 handleAsyncChannelHalfConnect(msg);
2197 break;
2198 }
2199 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2200 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2201 if (nai != null) nai.asyncChannel.disconnect();
2202 break;
2203 }
2204 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2205 handleAsyncChannelDisconnected(msg);
2206 break;
2207 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002208 }
2209 return true;
2210 }
2211
2212 private void maybeHandleNetworkAgentMessage(Message msg) {
2213 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2214 if (nai == null) {
2215 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002216 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002217 }
2218 return;
2219 }
2220
2221 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002223 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2224 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002225 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2226 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002227 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002228 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002229 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002230 break;
2231 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002232 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002233 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002234 break;
2235 }
2236 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002237 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 updateNetworkInfo(nai, info);
2239 break;
2240 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002241 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002242 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002243 break;
2244 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002245 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002246 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2247 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002248 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002249 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002250 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002251 break;
2252 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002253 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002254 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2255 break;
2256 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002257 }
2258 }
2259
2260 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2261 switch (msg.what) {
2262 default:
2263 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002264 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002265 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002266 if (nai == null) break;
2267
2268 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2269 final boolean wasValidated = nai.lastValidated;
2270 final boolean wasDefault = isDefaultNetwork(nai);
2271
Erik Klinea24d4592018-01-11 21:07:29 +09002272 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2273
Erik Klinea24d4592018-01-11 21:07:29 +09002274 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002275 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2276 ? " with redirect to " + redirectUrl
2277 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002278 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2279 }
Erik Klinea24d4592018-01-11 21:07:29 +09002280 if (valid != nai.lastValidated) {
2281 if (wasDefault) {
2282 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2283 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002284 }
Erik Klinea24d4592018-01-11 21:07:29 +09002285 final int oldScore = nai.getCurrentScore();
2286 nai.lastValidated = valid;
2287 nai.everValidated |= valid;
2288 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2289 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2290 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002291 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002292 }
2293 updateInetCondition(nai);
2294 // Let the NetworkAgent know the state of its network
2295 Bundle redirectUrlBundle = new Bundle();
2296 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2297 nai.asyncChannel.sendMessage(
2298 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2299 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2300 0, redirectUrlBundle);
2301 if (wasValidated && !nai.lastValidated) {
2302 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002303 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002304 break;
2305 }
Paul Jensen869868be2014-05-15 10:33:05 -04002306 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002307 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002308 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002309 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002310 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002311 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002312 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002313 nai.lastCaptivePortalDetected = visible;
2314 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002315 if (nai.lastCaptivePortalDetected &&
2316 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2317 if (DBG) log("Avoiding captive portal network: " + nai.name());
2318 nai.asyncChannel.sendMessage(
2319 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2320 teardownUnneededNetwork(nai);
2321 break;
2322 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002323 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002324 }
2325 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002326 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002327 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002328 if (nai == null) {
2329 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2330 break;
2331 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002332 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002333 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002334 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002335 }
Paul Jensen869868be2014-05-15 10:33:05 -04002336 }
Paul Jensen869868be2014-05-15 10:33:05 -04002337 break;
2338 }
Erik Klinea24d4592018-01-11 21:07:29 +09002339 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002341 if (nai == null) break;
2342
Erik Kline736353a2018-03-21 07:18:33 -07002343 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002344 break;
2345 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002346 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002347 return true;
2348 }
2349
Calvin Onbe96da12016-10-11 15:10:46 -07002350 private int getCaptivePortalMode() {
2351 return Settings.Global.getInt(mContext.getContentResolver(),
2352 Settings.Global.CAPTIVE_PORTAL_MODE,
2353 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2354 }
2355
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002356 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2357 switch (msg.what) {
2358 default:
2359 return false;
2360 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2361 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2362 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2363 handleLingerComplete(nai);
2364 }
2365 break;
2366 }
2367 }
2368 return true;
2369 }
2370
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002371 @Override
2372 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002373 if (!maybeHandleAsyncChannelMessage(msg) &&
2374 !maybeHandleNetworkMonitorMessage(msg) &&
2375 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002376 maybeHandleNetworkAgentMessage(msg);
2377 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002378 }
2379 }
2380
Erik Kline736353a2018-03-21 07:18:33 -07002381 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2382 return NetworkMonitor.isValidationRequired(
2383 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2384 }
2385
Erik Klinec6d00222018-06-26 18:53:43 +09002386 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2387 if (nai == null) return;
2388 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2389 // in order to restart a validation pass from within netd.
2390 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2391 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2392 updateDnses(nai.linkProperties, null, nai.network.netId);
2393 }
2394 }
2395
Erik Klinea24d4592018-01-11 21:07:29 +09002396 private void handlePrivateDnsSettingsChanged() {
2397 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2398
2399 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002400 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002401 if (networkRequiresValidation(nai)) {
2402 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2403 }
Erik Klinea24d4592018-01-11 21:07:29 +09002404 }
2405 }
2406
Erik Kline736353a2018-03-21 07:18:33 -07002407 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2408 // Private DNS only ever applies to networks that might provide
2409 // Internet access and therefore also require validation.
2410 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002411
Erik Kline736353a2018-03-21 07:18:33 -07002412 // Notify the NetworkMonitor thread in case it needs to cancel or
2413 // schedule DNS resolutions. If a DNS resolution is required the
2414 // result will be sent back to us.
2415 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2416
2417 // With Private DNS bypass support, we can proceed to update the
2418 // Private DNS config immediately, even if we're in strict mode
2419 // and have not yet resolved the provider name into a set of IPs.
2420 updatePrivateDns(nai, cfg);
2421 }
2422
2423 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2424 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002425 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002426 }
2427
dalyk7301aa42018-03-05 12:42:22 -05002428 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2429 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2430 if (nai == null) {
2431 return;
2432 }
2433 mDnsManager.updatePrivateDnsValidation(update);
2434 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2435 }
2436
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002437 private void updateLingerState(NetworkAgentInfo nai, long now) {
2438 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2439 // 2. If the network was lingering and there are now requests, unlinger it.
2440 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2441 // one lingered request, start lingering.
2442 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002443 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002444 if (DBG) log("Unlingering " + nai.name());
2445 nai.unlinger();
2446 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002447 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002448 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002449 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002450 nai.linger();
2451 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2452 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2453 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002454 }
2455
Robert Greenwalt7b816022014-04-18 15:25:25 -07002456 private void handleAsyncChannelHalfConnect(Message msg) {
2457 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002458 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002459 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2460 if (VDBG) log("NetworkFactory connected");
2461 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002462 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002463 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002464 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002465 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002466 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002467 }
2468 } else {
2469 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002470 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002471 }
2472 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2473 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2474 if (VDBG) log("NetworkAgent connected");
2475 // A network agent has requested a connection. Establish the connection.
2476 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2477 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2478 } else {
2479 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002480 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002481 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002482 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002483 synchronized (mNetworkForNetId) {
2484 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002485 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002486 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002487 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002488 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002489 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002490 }
2491 }
2492 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002493
Chalard Jean392971c2018-05-11 20:19:20 +09002494 // This is a no-op if it's called with a message designating a network that has
2495 // already been destroyed, because its reference will not be found in the relevant
2496 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002497 private void handleAsyncChannelDisconnected(Message msg) {
2498 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2499 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002500 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002501 } else {
2502 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2503 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002504 }
2505 }
2506
Chalard Jean392971c2018-05-11 20:19:20 +09002507 // Destroys a network, remove references to it from the internal state managed by
2508 // ConnectivityService, free its interfaces and clean up.
2509 // Must be called on the Handler thread.
2510 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2511 if (DBG) {
2512 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2513 }
2514 // A network agent has disconnected.
2515 // TODO - if we move the logic to the network agent (have them disconnect
2516 // because they lost all their requests or because their score isn't good)
2517 // then they would disconnect organically, report their new state and then
2518 // disconnect the channel.
2519 if (nai.networkInfo.isConnected()) {
2520 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2521 null, null);
2522 }
2523 final boolean wasDefault = isDefaultNetwork(nai);
2524 if (wasDefault) {
2525 mDefaultInetConditionPublished = 0;
2526 // Log default network disconnection before required book-keeping.
2527 // Let rematchAllNetworksAndRequests() below record a new default network event
2528 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2529 // whose timestamps tell how long it takes to recover a default network.
2530 long now = SystemClock.elapsedRealtime();
2531 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2532 }
2533 notifyIfacesChangedForNetworkStats();
2534 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2535 // by other networks that are already connected. Perhaps that can be done by
2536 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2537 // of rematchAllNetworksAndRequests
2538 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2539 mKeepaliveTracker.handleStopAllKeepalives(nai,
2540 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2541 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2542 // Disable wakeup packet monitoring for each interface.
2543 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2544 }
2545 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2546 mNetworkAgentInfos.remove(nai.messenger);
2547 nai.maybeStopClat();
2548 synchronized (mNetworkForNetId) {
2549 // Remove the NetworkAgent, but don't mark the netId as
2550 // available until we've told netd to delete it below.
2551 mNetworkForNetId.remove(nai.network.netId);
2552 }
2553 // Remove all previously satisfied requests.
2554 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2555 NetworkRequest request = nai.requestAt(i);
2556 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2557 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2558 clearNetworkForRequest(request.requestId);
2559 sendUpdatedScoreToFactories(request, 0);
2560 }
2561 }
2562 nai.clearLingerState();
2563 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
2564 removeDataActivityTracking(nai);
2565 notifyLockdownVpn(nai);
2566 ensureNetworkTransitionWakelock(nai.name());
2567 }
2568 mLegacyTypeTracker.remove(nai, wasDefault);
2569 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2570 updateAllVpnsCapabilities();
2571 }
2572 rematchAllNetworksAndRequests(null, 0);
2573 mLingerMonitor.noteDisconnect(nai);
2574 if (nai.created) {
2575 // Tell netd to clean up the configuration for this network
2576 // (routing rules, DNS, etc).
2577 // This may be slow as it requires a lot of netd shelling out to ip and
2578 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2579 // after we've rematched networks with requests which should make a potential
2580 // fallback network the default or requested a new network from the
2581 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2582 // long time.
2583 try {
2584 mNetd.removeNetwork(nai.network.netId);
2585 } catch (Exception e) {
2586 loge("Exception removing network: " + e);
2587 }
2588 mDnsManager.removeNetwork(nai.network);
2589 }
2590 synchronized (mNetworkForNetId) {
2591 mNetIdInUse.delete(nai.network.netId);
2592 }
2593 }
2594
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002595 // If this method proves to be too slow then we can maintain a separate
2596 // pendingIntent => NetworkRequestInfo map.
2597 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2598 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2599 Intent intent = pendingIntent.getIntent();
2600 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2601 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2602 if (existingPendingIntent != null &&
2603 existingPendingIntent.getIntent().filterEquals(intent)) {
2604 return entry.getValue();
2605 }
2606 }
2607 return null;
2608 }
2609
2610 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2611 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2612
2613 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2614 if (existingRequest != null) { // remove the existing request.
2615 if (DBG) log("Replacing " + existingRequest.request + " with "
2616 + nri.request + " because their intents matched.");
2617 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2618 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002619 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002620 }
2621
Erik Klineda4bfa82015-04-30 12:58:40 +09002622 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002623 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002624 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002625 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002626 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002627 if (nri.request.networkCapabilities.hasSignalStrength() &&
2628 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2629 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002630 }
2631 }
2632 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002633 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002634 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002635 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002636 }
2637 }
2638
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002639 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2640 int callingUid) {
2641 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2642 if (nri != null) {
2643 handleReleaseNetworkRequest(nri.request, callingUid);
2644 }
2645 }
2646
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002647 // Determines whether the network is the best (or could become the best, if it validated), for
2648 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2649 // on the value of reason:
2650 //
2651 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2652 // then it should be torn down.
2653 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2654 // then it should be lingered.
2655 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2656 final int numRequests;
2657 switch (reason) {
2658 case TEARDOWN:
2659 numRequests = nai.numRequestNetworkRequests();
2660 break;
2661 case LINGER:
2662 numRequests = nai.numForegroundNetworkRequests();
2663 break;
2664 default:
2665 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2666 return true;
2667 }
2668
2669 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002670 return false;
2671 }
Paul Jensene0988542015-06-25 15:30:08 -04002672 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002673 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2674 // Background requests don't affect lingering.
2675 continue;
2676 }
2677
Paul Jensene0988542015-06-25 15:30:08 -04002678 // If this Network is already the highest scoring Network for a request, or if
2679 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002680 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002681 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002682 // Note that this catches two important cases:
2683 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2684 // is currently satisfying the request. This is desirable when
2685 // cellular ends up validating but WiFi does not.
2686 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002687 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002688 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002689 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002690 nai.getCurrentScoreAsValidated())) {
2691 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002692 }
2693 }
Paul Jensene0988542015-06-25 15:30:08 -04002694 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002695 }
2696
Erik Klineacdd6392016-07-07 16:50:58 +09002697 private NetworkRequestInfo getNriForAppRequest(
2698 NetworkRequest request, int callingUid, String requestedOperation) {
2699 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2700
Robert Greenwalt9258c642014-03-26 16:47:06 -07002701 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002702 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002703 log(String.format("UID %d attempted to %s for unowned request %s",
2704 callingUid, requestedOperation, nri));
2705 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002706 }
Erik Klineacdd6392016-07-07 16:50:58 +09002707 }
2708
2709 return nri;
2710 }
2711
Erik Kline57faba92015-11-25 12:49:38 +09002712 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002713 if (mNetworkRequests.get(nri.request) == null) {
2714 return;
Erik Kline57faba92015-11-25 12:49:38 +09002715 }
Hugo Benichicd952782017-09-20 11:20:14 +09002716 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002717 return;
2718 }
2719 if (VDBG || (DBG && nri.request.isRequest())) {
2720 log("releasing " + nri.request + " (timeout)");
2721 }
2722 handleRemoveNetworkRequest(nri);
2723 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002724 }
2725
Erik Klineacdd6392016-07-07 16:50:58 +09002726 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002727 final NetworkRequestInfo nri =
2728 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2729 if (nri == null) {
2730 return;
Erik Kline57faba92015-11-25 12:49:38 +09002731 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002732 if (VDBG || (DBG && nri.request.isRequest())) {
2733 log("releasing " + nri.request + " (release request)");
2734 }
2735 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002736 }
Erik Klineacdd6392016-07-07 16:50:58 +09002737
Hugo Benichidba33db2017-03-23 22:40:44 +09002738 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002739 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002740 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002741
Erik Klineacdd6392016-07-07 16:50:58 +09002742 synchronized (mUidToNetworkRequestCount) {
2743 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2744 if (requests < 1) {
2745 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2746 nri.mUid);
2747 } else if (requests == 1) {
2748 mUidToNetworkRequestCount.removeAt(
2749 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2750 } else {
2751 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2752 }
2753 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002754
Erik Klineacdd6392016-07-07 16:50:58 +09002755 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2756 if (nri.request.isRequest()) {
2757 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002758 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002759 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002760 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002761 nai.removeRequest(nri.request.requestId);
2762 if (VDBG) {
2763 log(" Removing from current network " + nai.name() +
2764 ", leaving " + nai.numNetworkRequests() + " requests.");
2765 }
2766 // If there are still lingered requests on this network, don't tear it down,
2767 // but resume lingering instead.
2768 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002769 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002770 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2771 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002772 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002773 wasKept = true;
2774 }
Hugo Benichicd952782017-09-20 11:20:14 +09002775 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002776 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2777 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002778 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002779 }
Erik Klineacdd6392016-07-07 16:50:58 +09002780 }
2781
2782 // TODO: remove this code once we know that the Slog.wtf is never hit.
2783 //
2784 // Find all networks that are satisfying this request and remove the request
2785 // from their request lists.
2786 // TODO - it's my understanding that for a request there is only a single
2787 // network satisfying it, so this loop is wasteful
2788 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2789 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2790 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2791 otherNai.name() + ", but mNetworkAgentInfos says " +
2792 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002793 }
2794 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002795
Erik Klineacdd6392016-07-07 16:50:58 +09002796 // Maintain the illusion. When this request arrived, we might have pretended
2797 // that a network connected to serve it, even though the network was already
2798 // connected. Now that this request has gone away, we might have to pretend
2799 // that the network disconnected. LegacyTypeTracker will generate that
2800 // phantom disconnect for this type.
2801 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2802 boolean doRemove = true;
2803 if (wasKept) {
2804 // check if any of the remaining requests for this network are for the
2805 // same legacy type - if so, don't remove the nai
2806 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2807 NetworkRequest otherRequest = nai.requestAt(i);
2808 if (otherRequest.legacyType == nri.request.legacyType &&
2809 otherRequest.isRequest()) {
2810 if (DBG) log(" still have other legacy request - leaving");
2811 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002812 }
2813 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002814 }
2815
Erik Klineacdd6392016-07-07 16:50:58 +09002816 if (doRemove) {
2817 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002818 }
2819 }
Erik Klineacdd6392016-07-07 16:50:58 +09002820
2821 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2822 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2823 nri.request);
2824 }
2825 } else {
2826 // listens don't have a singular affectedNetwork. Check all networks to see
2827 // if this listen request applies and remove it.
2828 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2829 nai.removeRequest(nri.request.requestId);
2830 if (nri.request.networkCapabilities.hasSignalStrength() &&
2831 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2832 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2833 }
2834 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002835 }
2836 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002837
Lorenzo Colitti18660282016-07-04 12:55:44 +09002838 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002839 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2840 enforceConnectivityInternalPermission();
2841 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002842 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002843 }
2844
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002845 @Override
2846 public void setAvoidUnvalidated(Network network) {
2847 enforceConnectivityInternalPermission();
2848 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2849 }
2850
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002851 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2852 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2853 " accept=" + accept + " always=" + always);
2854
2855 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2856 if (nai == null) {
2857 // Nothing to do.
2858 return;
2859 }
2860
2861 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002862 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002863 return;
2864 }
2865
2866 if (!nai.networkMisc.explicitlySelected) {
2867 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2868 }
2869
2870 if (accept != nai.networkMisc.acceptUnvalidated) {
2871 int oldScore = nai.getCurrentScore();
2872 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002873 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002874 sendUpdatedScoreToFactories(nai);
2875 }
2876
2877 if (always) {
2878 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002879 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002880 }
2881
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002882 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002883 // Tell the NetworkAgent to not automatically reconnect to the network.
2884 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09002885 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04002886 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002887 }
2888
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002889 }
2890
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002891 private void handleSetAvoidUnvalidated(Network network) {
2892 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2893 if (nai == null || nai.lastValidated) {
2894 // Nothing to do. The network either disconnected or revalidated.
2895 return;
2896 }
2897 if (!nai.avoidUnvalidated) {
2898 int oldScore = nai.getCurrentScore();
2899 nai.avoidUnvalidated = true;
2900 rematchAllNetworksAndRequests(nai, oldScore);
2901 sendUpdatedScoreToFactories(nai);
2902 }
2903 }
2904
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002905 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002906 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002907 mHandler.sendMessageDelayed(
2908 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2909 PROMPT_UNVALIDATED_DELAY_MS);
2910 }
2911
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002912 @Override
2913 public void startCaptivePortalApp(Network network) {
2914 enforceConnectivityInternalPermission();
2915 mHandler.post(() -> {
2916 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2917 if (nai == null) return;
2918 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2919 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2920 });
2921 }
2922
Hugo Benichic8e9e122016-09-14 23:23:08 +00002923 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002924 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002925 }
2926
Erik Kline065ab6e2016-10-02 18:02:14 +09002927 private void rematchForAvoidBadWifiUpdate() {
2928 rematchAllNetworksAndRequests(null, 0);
2929 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2930 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2931 sendUpdatedScoreToFactories(nai);
2932 }
2933 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002934 }
2935
Erik Kline065ab6e2016-10-02 18:02:14 +09002936 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002937 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002938 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002939 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002940 if (!configRestrict) {
2941 pw.println("Bad Wi-Fi avoidance: unrestricted");
2942 return;
2943 }
2944
2945 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2946 pw.increaseIndent();
2947 pw.println("Config restrict: " + configRestrict);
2948
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002949 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002950 String description;
2951 // Can't use a switch statement because strings are legal case labels, but null is not.
2952 if ("0".equals(value)) {
2953 description = "get stuck";
2954 } else if (value == null) {
2955 description = "prompt";
2956 } else if ("1".equals(value)) {
2957 description = "avoid";
2958 } else {
2959 description = value + " (?)";
2960 }
2961 pw.println("User setting: " + description);
2962 pw.println("Network overrides:");
2963 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09002964 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002965 if (nai.avoidUnvalidated) {
2966 pw.println(nai.name());
2967 }
2968 }
2969 pw.decreaseIndent();
2970 pw.decreaseIndent();
2971 }
2972
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002973 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2974 final String action;
2975 switch (type) {
2976 case NO_INTERNET:
2977 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2978 break;
2979 case LOST_INTERNET:
2980 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2981 break;
2982 default:
2983 Slog.wtf(TAG, "Unknown notification type " + type);
2984 return;
2985 }
2986
2987 Intent intent = new Intent(action);
2988 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2989 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2990 intent.setClassName("com.android.settings",
2991 "com.android.settings.wifi.WifiNoInternetDialog");
2992
2993 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2994 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2995 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2996 }
2997
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002998 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002999 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003000 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3001
3002 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3003 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003004 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003005 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003006 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3007 return;
3008 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003009 showValidationNotification(nai, NotificationType.NO_INTERNET);
3010 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003011
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003012 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3013 NetworkCapabilities nc = nai.networkCapabilities;
3014 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003015
Erik Kline065ab6e2016-10-02 18:02:14 +09003016 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003017 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003018 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3019 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003020 }
3021
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003022 @Override
3023 public int getMultipathPreference(Network network) {
3024 enforceAccessPermission();
3025
3026 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003027 if (nai != null && nai.networkCapabilities
3028 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003029 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3030 }
3031
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003032 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3033 if (networkPreference != null) {
3034 return networkPreference;
3035 }
3036
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003037 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3038 }
3039
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003040 private class InternalHandler extends Handler {
3041 public InternalHandler(Looper looper) {
3042 super(looper);
3043 }
3044
3045 @Override
3046 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003047 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003048 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003049 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003050 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003051 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003052 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003053 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003054 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003055 break;
3056 }
Jason Monkdecd2952013-10-10 14:02:51 -04003057 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003058 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003059 break;
3060 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003061 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003062 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3063 break;
3064 }
3065 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3066 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003067 break;
3068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003069 case EVENT_REGISTER_NETWORK_AGENT: {
3070 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3071 break;
3072 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003073 case EVENT_REGISTER_NETWORK_REQUEST:
3074 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003075 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003076 break;
3077 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003078 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3079 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003080 handleRegisterNetworkRequestWithIntent(msg);
3081 break;
3082 }
Erik Kline57faba92015-11-25 12:49:38 +09003083 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3084 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3085 handleTimedOutNetworkRequest(nri);
3086 break;
3087 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003088 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3089 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3090 break;
3091 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003092 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003093 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003094 break;
3095 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003096 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003097 Network network = (Network) msg.obj;
3098 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003099 break;
3100 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003101 case EVENT_SET_AVOID_UNVALIDATED: {
3102 handleSetAvoidUnvalidated((Network) msg.obj);
3103 break;
3104 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003105 case EVENT_PROMPT_UNVALIDATED: {
3106 handlePromptUnvalidated((Network) msg.obj);
3107 break;
3108 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003109 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3110 handleMobileDataAlwaysOn();
3111 break;
3112 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003113 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3114 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3115 mKeepaliveTracker.handleStartKeepalive(msg);
3116 break;
3117 }
3118 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3119 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3120 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3121 int slot = msg.arg1;
3122 int reason = msg.arg2;
3123 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3124 break;
3125 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003126 case EVENT_SYSTEM_READY: {
3127 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3128 nai.networkMonitor.systemReady = true;
3129 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003130 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003131 break;
3132 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003133 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003134 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003135 break;
3136 }
Erik Klinea24d4592018-01-11 21:07:29 +09003137 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3138 handlePrivateDnsSettingsChanged();
3139 break;
dalyk7301aa42018-03-05 12:42:22 -05003140 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3141 handlePrivateDnsValidationUpdate(
3142 (PrivateDnsValidationUpdate) msg.obj);
3143 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 }
3145 }
3146 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003147
3148 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003149 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003150 public int tether(String iface, String callerPkg) {
3151 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003152 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003153 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003154 } else {
3155 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3156 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003157 }
3158
3159 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003160 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003161 public int untether(String iface, String callerPkg) {
3162 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003163
3164 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003165 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003166 } else {
3167 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3168 }
3169 }
3170
3171 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003172 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003173 public int getLastTetherError(String iface) {
3174 enforceTetherAccessPermission();
3175
3176 if (isTetheringSupported()) {
3177 return mTethering.getLastTetherError(iface);
3178 } else {
3179 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3180 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003181 }
3182
3183 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003184 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003185 public String[] getTetherableUsbRegexs() {
3186 enforceTetherAccessPermission();
3187 if (isTetheringSupported()) {
3188 return mTethering.getTetherableUsbRegexs();
3189 } else {
3190 return new String[0];
3191 }
3192 }
3193
Lorenzo Colitti18660282016-07-04 12:55:44 +09003194 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003195 public String[] getTetherableWifiRegexs() {
3196 enforceTetherAccessPermission();
3197 if (isTetheringSupported()) {
3198 return mTethering.getTetherableWifiRegexs();
3199 } else {
3200 return new String[0];
3201 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003202 }
3203
Lorenzo Colitti18660282016-07-04 12:55:44 +09003204 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003205 public String[] getTetherableBluetoothRegexs() {
3206 enforceTetherAccessPermission();
3207 if (isTetheringSupported()) {
3208 return mTethering.getTetherableBluetoothRegexs();
3209 } else {
3210 return new String[0];
3211 }
3212 }
3213
Lorenzo Colitti18660282016-07-04 12:55:44 +09003214 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003215 public int setUsbTethering(boolean enable, String callerPkg) {
3216 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003217 if (isTetheringSupported()) {
3218 return mTethering.setUsbTethering(enable);
3219 } else {
3220 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3221 }
3222 }
3223
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003224 // TODO - move iface listing, queries, etc to new module
3225 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003226 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003227 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003228 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003229 return mTethering.getTetherableIfaces();
3230 }
3231
Lorenzo Colitti18660282016-07-04 12:55:44 +09003232 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003233 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003234 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003235 return mTethering.getTetheredIfaces();
3236 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003237
Lorenzo Colitti18660282016-07-04 12:55:44 +09003238 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003239 public String[] getTetheringErroredIfaces() {
3240 enforceTetherAccessPermission();
3241 return mTethering.getErroredIfaces();
3242 }
3243
Lorenzo Colitti18660282016-07-04 12:55:44 +09003244 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003245 public String[] getTetheredDhcpRanges() {
3246 enforceConnectivityInternalPermission();
3247 return mTethering.getTetheredDhcpRanges();
3248 }
3249
Udam Saini0e94c362017-06-07 12:06:28 -07003250 @Override
3251 public boolean isTetheringSupported(String callerPkg) {
3252 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3253 return isTetheringSupported();
3254 }
3255
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003256 // if ro.tether.denied = true we default to no tethering
3257 // gservices could set the secure setting to 1 though to enable it on a build where it
3258 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003259 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003260 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3261 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3262 Settings.Global.TETHER_SUPPORTED, defaultVal));
3263 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003264 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003265
3266 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3267 boolean adminUser = false;
3268 final long token = Binder.clearCallingIdentity();
3269 try {
3270 adminUser = mUserManager.isAdminUser();
3271 } finally {
3272 Binder.restoreCallingIdentity(token);
3273 }
3274
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003275 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003276 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003277
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003278 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003279 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3280 String callerPkg) {
3281 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003282 if (!isTetheringSupported()) {
3283 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3284 return;
3285 }
3286 mTethering.startTethering(type, receiver, showProvisioningUi);
3287 }
3288
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003289 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003290 public void stopTethering(int type, String callerPkg) {
3291 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003292 mTethering.stopTethering(type);
3293 }
3294
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003295 // Called when we lose the default network and have no replacement yet.
3296 // This will automatically be cleared after X seconds or a new default network
3297 // becomes CONNECTED, whichever happens first. The timer is started by the
3298 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003299 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003300 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003301 if (mNetTransitionWakeLock.isHeld()) {
3302 return;
3303 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003304 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003305 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3306 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003307 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003308 mWakelockLogs.log("ACQUIRE for " + forWhom);
3309 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3310 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003311 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003312
Hugo Benichi4c31b342017-03-30 23:18:10 +09003313 // Called when we gain a new default network to release the network transition wakelock in a
3314 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3315 // message is cancelled.
3316 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003317 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003318 if (!mNetTransitionWakeLock.isHeld()) {
3319 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003320 }
3321 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003322 // Cancel self timeout on wakelock hold.
3323 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3324 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3325 mHandler.sendMessageDelayed(msg, 1000);
3326 }
3327
3328 // Called when either message of ensureNetworkTransitionWakelock or
3329 // scheduleReleaseNetworkTransitionWakelock is processed.
3330 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3331 String event = eventName(eventId);
3332 synchronized (this) {
3333 if (!mNetTransitionWakeLock.isHeld()) {
3334 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3335 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3336 return;
3337 }
3338 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003339 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3340 mTotalWakelockDurationMs += lockDuration;
3341 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3342 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003343 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003344 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003345 }
3346
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003347 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003348 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003349 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003350 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003351 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003352 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003353 }
3354
Lorenzo Colitti18660282016-07-04 12:55:44 +09003355 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003356 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003357 enforceAccessPermission();
3358 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003359 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003360 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003361 mHandler.sendMessage(
3362 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3363 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003364
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003365 private void handleReportNetworkConnectivity(
3366 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003367 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003368 if (network == null) {
3369 nai = getDefaultNetwork();
3370 } else {
3371 nai = getNetworkAgentInfoForNetwork(network);
3372 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003373 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3374 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3375 return;
3376 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003377 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003378 if (hasConnectivity == nai.lastValidated) {
3379 return;
3380 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003381 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003382 int netid = nai.network.netId;
3383 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003384 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003385 // Validating a network that has not yet connected could result in a call to
3386 // rematchNetworkAndRequests() which is not meant to work on such networks.
3387 if (!nai.everConnected) {
3388 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003389 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003390 LinkProperties lp = getLinkProperties(nai);
3391 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3392 return;
3393 }
Erik Kline736353a2018-03-21 07:18:33 -07003394 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003395 }
3396
Lorenzo Colitti18660282016-07-04 12:55:44 +09003397 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003398 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003399 if (network == null) return mProxyTracker.getDefaultProxy();
3400 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003401 if (globalProxy != null) return globalProxy;
3402 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3403 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3404 // caller may not have.
3405 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3406 if (nai == null) return null;
3407 synchronized (nai) {
3408 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3409 if (proxyInfo == null) return null;
3410 return new ProxyInfo(proxyInfo);
3411 }
3412 }
3413
Chalard Jean3c443fc2018-06-07 18:37:59 +09003414 @Override
3415 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003416 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003417 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003418 }
3419
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003420 private void loadGlobalProxy() {
3421 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003422 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3423 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3424 String exclList = Settings.Global.getString(res,
3425 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003426 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3427 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003428 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003429 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003430 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003431 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003432 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003433 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003434 if (!proxyProperties.isValid()) {
3435 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3436 return;
3437 }
3438
Chalard Jean52c2aa72018-06-07 16:44:04 +09003439 synchronized (mProxyTracker.mProxyLock) {
3440 mProxyTracker.mGlobalProxy = proxyProperties;
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003441 }
3442 }
3443 }
3444
Chalard Jean5afbc832018-06-07 18:02:37 +09003445 @Override
3446 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003447 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003448 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003449 }
3450
Jason Monk207900c2014-04-25 15:00:09 -04003451 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003452 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003453 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003454 proxy = null;
3455 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003456 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003457 }
3458
Paul Jensene0bef712014-12-10 15:12:18 -05003459 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3460 // This method gets called when any network changes proxy, but the broadcast only ever contains
3461 // the default proxy (even if it hasn't changed).
3462 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3463 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003464 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003465 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3466 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3467
Chalard Jean4949dd72018-06-07 17:41:29 +09003468 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003469 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003470 }
3471 }
3472
Robert Greenwalt434203a2010-10-11 16:00:27 -07003473 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003474 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003475 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 if (!TextUtils.isEmpty(proxy)) {
3477 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003478 if (data.length == 0) {
3479 return;
3480 }
3481
Chalard Jean4133a122018-06-04 13:33:12 +09003482 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003483 int proxyPort = 8080;
3484 if (data.length > 1) {
3485 try {
3486 proxyPort = Integer.parseInt(data[1]);
3487 } catch (NumberFormatException e) {
3488 return;
3489 }
3490 }
Chalard Jean4133a122018-06-04 13:33:12 +09003491 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003492 setGlobalProxy(p);
3493 }
3494 }
3495
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003497 final private HashMap<Uri, Integer> mUriEventMap;
3498 final private Context mContext;
3499 final private Handler mHandler;
3500
3501 SettingsObserver(Context context, Handler handler) {
3502 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003503 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003504 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003505 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003506 }
3507
Erik Klineda4bfa82015-04-30 12:58:40 +09003508 void observe(Uri uri, int what) {
3509 mUriEventMap.put(uri, what);
3510 final ContentResolver resolver = mContext.getContentResolver();
3511 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003512 }
3513
3514 @Override
3515 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003516 Slog.wtf(TAG, "Should never be reached.");
3517 }
3518
3519 @Override
3520 public void onChange(boolean selfChange, Uri uri) {
3521 final Integer what = mUriEventMap.get(uri);
3522 if (what != null) {
3523 mHandler.obtainMessage(what.intValue()).sendToTarget();
3524 } else {
3525 loge("No matching event to send for URI=" + uri);
3526 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003527 }
3528 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003529
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003530 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003531 Slog.d(TAG, s);
3532 }
3533
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003534 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003535 Slog.e(TAG, s);
3536 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003537
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003538 private static void loge(String s, Throwable t) {
3539 Slog.e(TAG, s, t);
3540 }
3541
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003542 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003543 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003544 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3545 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3546 *
3547 * @param oldPackage Package name of the application which currently controls VPN, which will
3548 * be replaced. If there is no such application, this should should either be
3549 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3550 * @param newPackage Package name of the application which should gain control of VPN, or
3551 * {@code null} to disable.
3552 * @param userId User for whom to prepare the new VPN.
3553 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003554 * @hide
3555 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003556 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003557 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3558 int userId) {
3559 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003560
Hugo Benichi20035e02017-04-26 14:53:28 +09003561 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003562 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003563 Vpn vpn = mVpns.get(userId);
3564 if (vpn != null) {
3565 return vpn.prepare(oldPackage, newPackage);
3566 } else {
3567 return false;
3568 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003569 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003570 }
3571
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003572 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003573 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3574 * This method is used by system-privileged apps.
3575 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3576 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3577 *
3578 * @param packageName The package for which authorization state should change.
3579 * @param userId User for whom {@code packageName} is installed.
3580 * @param authorized {@code true} if this app should be able to start a VPN connection without
3581 * explicit user approval, {@code false} if not.
3582 *
Jeff Davidson05542602014-08-11 14:07:27 -07003583 * @hide
3584 */
3585 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003586 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3587 enforceCrossUserPermission(userId);
3588
Hugo Benichi20035e02017-04-26 14:53:28 +09003589 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003590 Vpn vpn = mVpns.get(userId);
3591 if (vpn != null) {
3592 vpn.setPackageAuthorization(packageName, authorized);
3593 }
Jeff Davidson05542602014-08-11 14:07:27 -07003594 }
3595 }
3596
3597 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003598 * Configure a TUN interface and return its file descriptor. Parameters
3599 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003600 * and not available in ConnectivityManager. Permissions are checked in
3601 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003602 * @hide
3603 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003604 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003605 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003606 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003607 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003608 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003609 return mVpns.get(user).establish(config);
3610 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003611 }
3612
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003613 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003614 * Start legacy VPN, controlling native daemons as needed. Creates a
3615 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003616 */
3617 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003618 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003619 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003620 final LinkProperties egress = getActiveLinkProperties();
3621 if (egress == null) {
3622 throw new IllegalStateException("Missing active network connection");
3623 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003624 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003625 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003626 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3627 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003628 }
3629
3630 /**
3631 * Return the information of the ongoing legacy VPN. This method is used
3632 * by VpnSettings and not available in ConnectivityManager. Permissions
3633 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003634 */
3635 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003636 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3637 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003638
Hugo Benichi20035e02017-04-26 14:53:28 +09003639 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003640 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003641 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003642 }
3643
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003644 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003645 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3646 * and not available in ConnectivityManager.
3647 */
3648 @Override
3649 public VpnInfo[] getAllVpnInfo() {
3650 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003651 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003652 if (mLockdownEnabled) {
3653 return new VpnInfo[0];
3654 }
3655
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003656 List<VpnInfo> infoList = new ArrayList<>();
3657 for (int i = 0; i < mVpns.size(); i++) {
3658 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3659 if (info != null) {
3660 infoList.add(info);
3661 }
3662 }
3663 return infoList.toArray(new VpnInfo[infoList.size()]);
3664 }
3665 }
3666
3667 /**
3668 * @return VPN information for accounting, or null if we can't retrieve all required
3669 * information, e.g primary underlying iface.
3670 */
3671 @Nullable
3672 private VpnInfo createVpnInfo(Vpn vpn) {
3673 VpnInfo info = vpn.getVpnInfo();
3674 if (info == null) {
3675 return null;
3676 }
3677 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3678 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3679 // the underlyingNetworks list.
3680 if (underlyingNetworks == null) {
3681 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3682 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3683 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3684 }
3685 } else if (underlyingNetworks.length > 0) {
3686 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3687 if (linkProperties != null) {
3688 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3689 }
3690 }
3691 return info.primaryUnderlyingIface == null ? null : info;
3692 }
3693
3694 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003695 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3696 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003697 * Permissions are checked in Vpn class.
3698 * @hide
3699 */
3700 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003701 public VpnConfig getVpnConfig(int userId) {
3702 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003703 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003704 Vpn vpn = mVpns.get(userId);
3705 if (vpn != null) {
3706 return vpn.getVpnConfig();
3707 } else {
3708 return null;
3709 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003710 }
3711 }
3712
Chalard Jean6b65ec72018-05-18 22:02:56 +09003713 /**
3714 * Ask all VPN objects to recompute and update their capabilities.
3715 *
3716 * When underlying networks change, VPNs may have to update capabilities to reflect things
3717 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3718 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3719 * handler thread through their agent, this is asynchronous. When the capabilities objects
3720 * are computed they will be up-to-date as they are computed synchronously from here and
3721 * this is running on the ConnectivityService thread.
3722 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3723 */
3724 private void updateAllVpnsCapabilities() {
3725 synchronized (mVpns) {
3726 for (int i = 0; i < mVpns.size(); i++) {
3727 final Vpn vpn = mVpns.valueAt(i);
3728 vpn.updateCapabilities();
3729 }
3730 }
3731 }
3732
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003733 @Override
3734 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003735 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3736 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3737 return false;
3738 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003739
Hugo Benichi69744342017-11-27 10:57:16 +09003740 synchronized (mVpns) {
3741 // Tear down existing lockdown if profile was removed
3742 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3743 if (mLockdownEnabled) {
3744 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3745 if (profileTag == null) {
3746 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3747 return false;
3748 }
3749 String profileName = new String(profileTag);
3750 final VpnProfile profile = VpnProfile.decode(
3751 profileName, mKeyStore.get(Credentials.VPN + profileName));
3752 if (profile == null) {
3753 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3754 setLockdownTracker(null);
3755 return true;
3756 }
3757 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003758 Vpn vpn = mVpns.get(user);
3759 if (vpn == null) {
3760 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3761 return false;
3762 }
3763 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003764 } else {
3765 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003766 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003767 }
3768
3769 return true;
3770 }
3771
3772 /**
3773 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3774 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3775 */
Hugo Benichi69744342017-11-27 10:57:16 +09003776 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003777 private void setLockdownTracker(LockdownVpnTracker tracker) {
3778 // Shutdown any existing tracker
3779 final LockdownVpnTracker existing = mLockdownTracker;
3780 mLockdownTracker = null;
3781 if (existing != null) {
3782 existing.shutdown();
3783 }
3784
Robin Leec3736bc2017-03-10 16:19:54 +00003785 if (tracker != null) {
3786 mLockdownTracker = tracker;
3787 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003788 }
3789 }
3790
Hugo Benichi69744342017-11-27 10:57:16 +09003791 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003792 private void throwIfLockdownEnabled() {
3793 if (mLockdownEnabled) {
3794 throw new IllegalStateException("Unavailable in lockdown mode");
3795 }
3796 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003797
Robin Lee244ce8e2016-01-05 18:03:46 +00003798 /**
Robin Lee17e61832016-05-09 13:46:28 +01003799 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3800 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003801 *
Robin Lee17e61832016-05-09 13:46:28 +01003802 * @return {@code true} if the service was started, the service was already connected, or there
3803 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003804 */
Robin Lee17e61832016-05-09 13:46:28 +01003805 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003806 synchronized (mVpns) {
3807 Vpn vpn = mVpns.get(userId);
3808 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003809 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003810 // exists already.
3811 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3812 return false;
3813 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003814
Robin Lee812800c2016-05-13 15:38:08 +01003815 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003816 }
3817 }
3818
3819 @Override
Charles He36738632017-05-15 17:07:18 +01003820 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3821 enforceSettingsPermission();
3822 enforceCrossUserPermission(userId);
3823
3824 synchronized (mVpns) {
3825 Vpn vpn = mVpns.get(userId);
3826 if (vpn == null) {
3827 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3828 return false;
3829 }
3830 return vpn.isAlwaysOnPackageSupported(packageName);
3831 }
3832 }
3833
3834 @Override
Robin Leedc679712016-05-03 13:23:03 +01003835 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003836 enforceConnectivityInternalPermission();
3837 enforceCrossUserPermission(userId);
3838
Robin Lee244ce8e2016-01-05 18:03:46 +00003839 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003840 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3841 if (LockdownVpnTracker.isEnabled()) {
3842 return false;
3843 }
3844
Robin Lee244ce8e2016-01-05 18:03:46 +00003845 Vpn vpn = mVpns.get(userId);
3846 if (vpn == null) {
3847 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3848 return false;
3849 }
Robin Lee17e61832016-05-09 13:46:28 +01003850 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003851 return false;
3852 }
Robin Lee17e61832016-05-09 13:46:28 +01003853 if (!startAlwaysOnVpn(userId)) {
3854 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 return false;
3856 }
3857 }
3858 return true;
3859 }
3860
3861 @Override
3862 public String getAlwaysOnVpnPackage(int userId) {
3863 enforceConnectivityInternalPermission();
3864 enforceCrossUserPermission(userId);
3865
3866 synchronized (mVpns) {
3867 Vpn vpn = mVpns.get(userId);
3868 if (vpn == null) {
3869 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3870 return null;
3871 }
3872 return vpn.getAlwaysOnPackage();
3873 }
3874 }
3875
Wink Savilleab9321d2013-06-29 21:10:57 -07003876 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003877 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003878 // TODO: Remove? Any reason to trigger a provisioning check?
3879 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003880 }
3881
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003882 /** Location to an updatable file listing carrier provisioning urls.
3883 * An example:
3884 *
3885 * <?xml version="1.0" encoding="utf-8"?>
3886 * <provisioningUrls>
3887 * <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 -07003888 * </provisioningUrls>
3889 */
3890 private static final String PROVISIONING_URL_PATH =
3891 "/data/misc/radio/provisioning_urls.xml";
3892 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003893
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003894 /** XML tag for root element. */
3895 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3896 /** XML tag for individual url */
3897 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003898 /** XML attribute for mcc */
3899 private static final String ATTR_MCC = "mcc";
3900 /** XML attribute for mnc */
3901 private static final String ATTR_MNC = "mnc";
3902
Paul Jensen434dde82015-06-11 09:43:30 -04003903 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003904 FileReader fileReader = null;
3905 XmlPullParser parser = null;
3906 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003907
3908 try {
3909 fileReader = new FileReader(mProvisioningUrlFile);
3910 parser = Xml.newPullParser();
3911 parser.setInput(fileReader);
3912 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3913
3914 while (true) {
3915 XmlUtils.nextElement(parser);
3916
3917 String element = parser.getName();
3918 if (element == null) break;
3919
Paul Jensen434dde82015-06-11 09:43:30 -04003920 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003921 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3922 try {
3923 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3924 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3925 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3926 parser.next();
3927 if (parser.getEventType() == XmlPullParser.TEXT) {
3928 return parser.getText();
3929 }
3930 }
3931 }
3932 } catch (NumberFormatException e) {
3933 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3934 }
3935 }
3936 }
3937 return null;
3938 } catch (FileNotFoundException e) {
3939 loge("Carrier Provisioning Urls file not found");
3940 } catch (XmlPullParserException e) {
3941 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3942 } catch (IOException e) {
3943 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3944 } finally {
3945 if (fileReader != null) {
3946 try {
3947 fileReader.close();
3948 } catch (IOException e) {}
3949 }
3950 }
3951 return null;
3952 }
3953
Wink Saville42d4f082013-07-20 20:31:59 -07003954 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003955 public String getMobileProvisioningUrl() {
3956 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003957 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003958 if (TextUtils.isEmpty(url)) {
3959 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003960 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003961 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003962 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003963 }
Wink Saville8cf35602013-07-10 23:00:07 -07003964 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003965 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003966 String phoneNumber = mTelephonyManager.getLine1Number();
3967 if (TextUtils.isEmpty(phoneNumber)) {
3968 phoneNumber = "0000000000";
3969 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003970 url = String.format(url,
3971 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3972 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09003973 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003974 }
3975
Wink Savilleab9321d2013-06-29 21:10:57 -07003976 return url;
3977 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003978
Wink Saville948282b2013-08-29 08:55:16 -07003979 @Override
3980 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003981 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003982 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003983 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3984 return;
3985 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003986 final long ident = Binder.clearCallingIdentity();
3987 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003988 // Concatenate the range of types onto the range of NetIDs.
3989 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3990 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003991 } finally {
3992 Binder.restoreCallingIdentity(ident);
3993 }
Wink Saville948282b2013-08-29 08:55:16 -07003994 }
Wink Saville7788c612013-08-29 14:57:08 -07003995
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003996 @Override
3997 public void setAirplaneMode(boolean enable) {
3998 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003999 final long ident = Binder.clearCallingIdentity();
4000 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004001 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004002 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004003 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4004 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004005 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
4009 }
4010
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004011 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004012 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004013 Vpn userVpn = mVpns.get(userId);
4014 if (userVpn != null) {
4015 loge("Starting user already has a VPN");
4016 return;
4017 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004018 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004019 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004020 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4021 updateLockdownVpn();
4022 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004023 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004024 }
4025
4026 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004027 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004028 Vpn userVpn = mVpns.get(userId);
4029 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004030 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004031 return;
4032 }
Robin Lee17e61832016-05-09 13:46:28 +01004033 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004034 mVpns.delete(userId);
4035 }
4036 }
4037
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004038 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004039 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004040 final int vpnsSize = mVpns.size();
4041 for (int i = 0; i < vpnsSize; i++) {
4042 Vpn vpn = mVpns.valueAt(i);
4043 vpn.onUserAdded(userId);
4044 }
4045 }
4046 }
4047
4048 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004049 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004050 final int vpnsSize = mVpns.size();
4051 for (int i = 0; i < vpnsSize; i++) {
4052 Vpn vpn = mVpns.valueAt(i);
4053 vpn.onUserRemoved(userId);
4054 }
4055 }
4056 }
4057
Robin Lee89e7a692016-02-29 14:38:17 +00004058 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004059 synchronized (mVpns) {
4060 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4061 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4062 updateLockdownVpn();
4063 } else {
4064 startAlwaysOnVpn(userId);
4065 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004066 }
4067 }
4068
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004069 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4070 @Override
4071 public void onReceive(Context context, Intent intent) {
4072 final String action = intent.getAction();
4073 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4074 if (userId == UserHandle.USER_NULL) return;
4075
Robin Lee323f29d2016-05-04 16:38:06 +01004076 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004077 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004078 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004079 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004080 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4081 onUserAdded(userId);
4082 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4083 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004084 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4085 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004086 }
4087 }
4088 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004089
Robin Lee95204e02017-01-27 11:59:22 +00004090 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4091 @Override
4092 public void onReceive(Context context, Intent intent) {
4093 // Try creating lockdown tracker, since user present usually means
4094 // unlocked keystore.
4095 updateLockdownVpn();
4096 mContext.unregisterReceiver(this);
4097 }
4098 };
4099
Chalard Jean4133a122018-06-04 13:33:12 +09004100 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4101 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004102
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004103 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4104 // Map from UID to number of NetworkRequests that UID has filed.
4105 @GuardedBy("mUidToNetworkRequestCount")
4106 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4107
Robert Greenwalta67be032014-05-16 15:49:14 -07004108 private static class NetworkFactoryInfo {
4109 public final String name;
4110 public final Messenger messenger;
4111 public final AsyncChannel asyncChannel;
4112
4113 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4114 this.name = name;
4115 this.messenger = messenger;
4116 this.asyncChannel = asyncChannel;
4117 }
4118 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004120 private void ensureNetworkRequestHasType(NetworkRequest request) {
4121 if (request.type == NetworkRequest.Type.NONE) {
4122 throw new IllegalArgumentException(
4123 "All NetworkRequests in ConnectivityService must have a type");
4124 }
4125 }
4126
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004127 /**
4128 * Tracks info about the requester.
4129 * Also used to notice when the calling process dies so we can self-expire
4130 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004132 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004133 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004134 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004136 final int mPid;
4137 final int mUid;
4138 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004140 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004141 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004142 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004143 mPendingIntent = pi;
4144 messenger = null;
4145 mBinder = null;
4146 mPid = getCallingPid();
4147 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004148 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 }
4150
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004151 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152 super();
4153 messenger = m;
4154 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004155 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156 mBinder = binder;
4157 mPid = getCallingPid();
4158 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004159 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004160 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004161
4162 try {
4163 mBinder.linkToDeath(this, 0);
4164 } catch (RemoteException e) {
4165 binderDied();
4166 }
4167 }
4168
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004169 private void enforceRequestCountLimit() {
4170 synchronized (mUidToNetworkRequestCount) {
4171 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4172 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004173 throw new ServiceSpecificException(
4174 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004175 }
4176 mUidToNetworkRequestCount.put(mUid, networkRequests);
4177 }
4178 }
4179
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004181 if (mBinder != null) {
4182 mBinder.unlinkToDeath(this, 0);
4183 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184 }
4185
4186 public void binderDied() {
4187 log("ConnectivityService NetworkRequestInfo binderDied(" +
4188 request + ", " + mBinder + ")");
4189 releaseNetworkRequest(request);
4190 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004191
4192 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004193 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004194 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196 }
4197
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004198 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4199 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4200 if (badCapability != null) {
4201 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004202 }
4203 }
4204
Chalard Jeanb03a6222018-04-11 21:09:10 +09004205 // This checks that the passed capabilities either do not request a specific SSID, or the
4206 // calling app has permission to do so.
4207 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4208 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004209 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004210 throw new SecurityException("Insufficient permissions to request a specific SSID");
4211 }
4212 }
4213
Erik Kline9d598e12015-07-13 16:37:51 +09004214 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004215 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004216 synchronized (nai) {
4217 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4218 if (nri.request.networkCapabilities.hasSignalStrength() &&
4219 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4220 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4221 }
4222 }
4223 }
Chalard Jean4133a122018-06-04 13:33:12 +09004224 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004225 }
4226
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004227 private void updateSignalStrengthThresholds(
4228 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4229 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004230 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004231 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4232
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004233 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004234 String detail;
4235 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4236 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4237 } else {
4238 detail = reason;
4239 }
4240 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4241 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4242 }
4243
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004244 nai.asyncChannel.sendMessage(
4245 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004246 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004247 }
4248
Etan Cohen859748f2017-04-03 17:42:34 -07004249 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4250 if (nc == null) {
4251 return;
4252 }
4253 NetworkSpecifier ns = nc.getNetworkSpecifier();
4254 if (ns == null) {
4255 return;
4256 }
4257 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4258 ns.assertValidFromUid(Binder.getCallingUid());
4259 }
4260
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261 @Override
4262 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004263 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004264 final NetworkRequest.Type type = (networkCapabilities == null)
4265 ? NetworkRequest.Type.TRACK_DEFAULT
4266 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004267 // If the requested networkCapabilities is null, take them instead from
4268 // the default network request. This allows callers to keep track of
4269 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004270 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004271 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004272 enforceAccessPermission();
4273 } else {
4274 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4275 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004276 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4277 // of the app when the request is filed, but we never change the request if the app
4278 // changes network state. http://b/29964605
4279 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004280 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004281 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004282 ensureSufficientPermissionsForRequest(networkCapabilities,
4283 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004284 // Set the UID range for this request to the single UID of the requester, or to an empty
4285 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004286 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4287 // are no visible methods to set the UIDs, an app could use reflection to try and get
4288 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004289 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004290
Etan Cohenba07c8c2017-02-05 10:42:27 -08004291 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004292 throw new IllegalArgumentException("Bad timeout specified");
4293 }
Etan Cohen859748f2017-04-03 17:42:34 -07004294 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004295
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004296 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004297 nextNetworkRequestId(), type);
4298 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004299 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004300
4301 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004302 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004303 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004304 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004305 }
4306 return networkRequest;
4307 }
4308
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004309 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004310 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004311 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004312 } else {
4313 enforceChangePermission();
4314 }
4315 }
4316
fenglub15e72b2015-03-20 11:29:56 -07004317 @Override
fengludb571472015-04-21 17:12:05 -07004318 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004319 enforceAccessPermission();
4320 NetworkAgentInfo nai = null;
4321 if (network == null) {
4322 return false;
4323 }
4324 synchronized (mNetworkForNetId) {
4325 nai = mNetworkForNetId.get(network.netId);
4326 }
4327 if (nai != null) {
4328 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004329 synchronized (mBandwidthRequests) {
4330 final int uid = Binder.getCallingUid();
4331 Integer uidReqs = mBandwidthRequests.get(uid);
4332 if (uidReqs == null) {
4333 uidReqs = new Integer(0);
4334 }
4335 mBandwidthRequests.put(uid, ++uidReqs);
4336 }
fenglub15e72b2015-03-20 11:29:56 -07004337 return true;
4338 }
4339 return false;
4340 }
4341
Felipe Lemeee27cab2016-06-20 16:36:29 -07004342 private boolean isSystem(int uid) {
4343 return uid < Process.FIRST_APPLICATION_UID;
4344 }
fenglub15e72b2015-03-20 11:29:56 -07004345
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004346 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004347 final int uid = Binder.getCallingUid();
4348 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004349 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004350 return;
4351 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004352 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4353 // Policy already enforced.
4354 return;
4355 }
4356 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4357 // If UID is restricted, don't allow them to bring up metered APNs.
4358 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004359 }
4360 }
4361
Robert Greenwalt9258c642014-03-26 16:47:06 -07004362 @Override
4363 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4364 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004365 checkNotNull(operation, "PendingIntent cannot be null.");
4366 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4367 enforceNetworkRequestPermissions(networkCapabilities);
4368 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004369 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004370 ensureSufficientPermissionsForRequest(networkCapabilities,
4371 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004372 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004373 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004374
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004375 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004376 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4377 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004378 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004379 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4380 nri));
4381 return networkRequest;
4382 }
4383
Jeremy Joslin79294842014-12-03 17:15:28 -08004384 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4385 mHandler.sendMessageDelayed(
4386 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4387 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4388 }
4389
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004390 @Override
4391 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004392 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004393 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4394 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004395 }
4396
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004397 // In order to implement the compatibility measure for pre-M apps that call
4398 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4399 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4400 // This ensures it has permission to do so.
4401 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4402 if (nc == null) {
4403 return false;
4404 }
4405 int[] transportTypes = nc.getTransportTypes();
4406 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4407 return false;
4408 }
4409 try {
4410 mContext.enforceCallingOrSelfPermission(
4411 android.Manifest.permission.ACCESS_WIFI_STATE,
4412 "ConnectivityService");
4413 } catch (SecurityException e) {
4414 return false;
4415 }
4416 return true;
4417 }
4418
Robert Greenwalt9258c642014-03-26 16:47:06 -07004419 @Override
4420 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4421 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004422 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4423 enforceAccessPermission();
4424 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004425
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004426 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004427 ensureSufficientPermissionsForRequest(networkCapabilities,
4428 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004429 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004430 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4431 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4432 // onLost and onAvailable callbacks when networks move in and out of the background.
4433 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4434 // can't request networks.
4435 restrictBackgroundRequestForCaller(nc);
4436 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004437
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004438 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004439 NetworkRequest.Type.LISTEN);
4440 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004441 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004442
4443 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4444 return networkRequest;
4445 }
4446
4447 @Override
4448 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4449 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004450 checkNotNull(operation, "PendingIntent cannot be null.");
4451 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4452 enforceAccessPermission();
4453 }
Etan Cohen859748f2017-04-03 17:42:34 -07004454 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004455 ensureSufficientPermissionsForRequest(networkCapabilities,
4456 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004457
Chalard Jeandda156a2018-01-10 21:19:32 +09004458 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004459 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004460
4461 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004462 NetworkRequest.Type.LISTEN);
4463 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004464 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004465
4466 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004467 }
4468
Erik Klineacdd6392016-07-07 16:50:58 +09004469 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004470 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004471 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004472 mHandler.sendMessage(mHandler.obtainMessage(
4473 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004474 }
4475
4476 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004477 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004478 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004479 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4480 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004481 }
4482
Robert Greenwalta67be032014-05-16 15:49:14 -07004483 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004484 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004485 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4486 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4487 }
4488
4489 @Override
4490 public void unregisterNetworkFactory(Messenger messenger) {
4491 enforceConnectivityInternalPermission();
4492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4493 }
4494
4495 private void handleUnregisterNetworkFactory(Messenger messenger) {
4496 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4497 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004498 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004499 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004500 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004501 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004502 }
4503
Robert Greenwalt7b816022014-04-18 15:25:25 -07004504 /**
4505 * NetworkAgentInfo supporting a request by requestId.
4506 * These have already been vetted (their Capabilities satisfy the request)
4507 * and the are the highest scored network available.
4508 * the are keyed off the Requests requestId.
4509 */
Hugo Benichicd952782017-09-20 11:20:14 +09004510 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4511 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004512 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004513
Paul Jensen31a94f42015-02-13 14:18:39 -05004514 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4515 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004516 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004517 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4518 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4519 // there may not be a strict 1:1 correlation between the two.
4520 @GuardedBy("mNetworkForNetId")
4521 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004522
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 // NetworkAgentInfo keyed off its connecting messenger
4524 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004525 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004526 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004528 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004529 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004530
Paul Jensen2c311d62014-11-17 12:34:51 -05004531 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004533
Erik Klineda4bfa82015-04-30 12:58:40 +09004534 // Request used to optionally keep mobile data active even when higher
4535 // priority networks like Wi-Fi are active.
4536 private final NetworkRequest mDefaultMobileDataRequest;
4537
Hugo Benichicd952782017-09-20 11:20:14 +09004538 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4539 synchronized (mNetworkForRequestId) {
4540 return mNetworkForRequestId.get(requestId);
4541 }
4542 }
4543
4544 private void clearNetworkForRequest(int requestId) {
4545 synchronized (mNetworkForRequestId) {
4546 mNetworkForRequestId.remove(requestId);
4547 }
4548 }
4549
4550 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4551 synchronized (mNetworkForRequestId) {
4552 mNetworkForRequestId.put(requestId, nai);
4553 }
4554 }
4555
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004556 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004557 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004558 }
4559
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004560 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004561 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004562 }
4563
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004564 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4565 return nri.request.requestId == mDefaultRequest.requestId;
4566 }
4567
Paul Jensen31a94f42015-02-13 14:18:39 -05004568 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004570 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004571 enforceConnectivityInternalPermission();
4572
Rubin Xu1bb5c082017-09-05 18:40:49 +01004573 LinkProperties lp = new LinkProperties(linkProperties);
4574 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004575 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4576 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004577 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004578 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004579 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004580 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004581 // Make sure the network capabilities reflect what the agent info says.
4582 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004583 synchronized (this) {
4584 nai.networkMonitor.systemReady = mSystemReady;
4585 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004586 final String extraInfo = networkInfo.getExtraInfo();
4587 final String name = TextUtils.isEmpty(extraInfo)
4588 ? nai.networkCapabilities.getSSID() : extraInfo;
4589 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004590 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004591 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004592 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 }
4594
Erik Klinee5dac902018-03-04 21:01:01 +09004595 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004596 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004597 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004598 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004599 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004600 }
Erik Klinee5dac902018-03-04 21:01:01 +09004601 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4602 NetworkInfo networkInfo = nai.networkInfo;
4603 nai.networkInfo = null;
4604 updateNetworkInfo(nai, networkInfo);
4605 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 }
4607
4608 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004609 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004610 int netId = networkAgent.network.netId;
4611
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004612 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4613 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004614 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004615 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004616 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004617
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004618 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 updateMtu(newLp, oldLp);
4620 // TODO - figure out what to do for clat
4621// for (LinkProperties lp : newLp.getStackedLinks()) {
4622// updateMtu(lp, null);
4623// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004624 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004625
Erik Kline94887872016-04-05 13:30:49 +09004626 updateRoutes(newLp, oldLp, netId);
4627 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004628 // Make sure LinkProperties represents the latest private DNS status.
4629 // This does not need to be done before updateDnses because the
4630 // LinkProperties are not the source of the private DNS configuration.
4631 // updateDnses will fetch the private DNS configuration from DnsManager.
4632 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004633
Hugo Benichi6f62b732017-06-27 15:13:20 +09004634 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004635 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004636 if (isDefaultNetwork(networkAgent)) {
4637 handleApplyDefaultProxy(newLp.getHttpProxy());
4638 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004639 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004640 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004641 // TODO - move this check to cover the whole function
4642 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004643 synchronized (networkAgent) {
4644 networkAgent.linkProperties = newLp;
4645 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004646 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004647 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4648 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004649
4650 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004651 }
4652
Joel Scherpelz668370b2017-06-08 15:35:21 +09004653 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004654 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004655 // marks on unsupported interfaces is harmless.
4656 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4657 return;
4658 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004659
Joel Scherpelz668370b2017-06-08 15:35:21 +09004660 int mark = mContext.getResources().getInteger(
4661 com.android.internal.R.integer.config_networkWakeupPacketMark);
4662 int mask = mContext.getResources().getInteger(
4663 com.android.internal.R.integer.config_networkWakeupPacketMask);
4664
4665 // Mask/mark of zero will not detect anything interesting.
4666 // Don't install rules unless both values are nonzero.
4667 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004668 return;
4669 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004670
4671 final String prefix = "iface:" + iface;
4672 try {
4673 if (add) {
4674 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4675 } else {
4676 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4677 }
4678 } catch (Exception e) {
4679 loge("Exception modifying wakeup packet monitoring: " + e);
4680 }
4681
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004682 }
4683
4684 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4685 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004686 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004687 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4688 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004689 for (String iface : interfaceDiff.added) {
4690 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004691 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004692 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004693 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004694 } catch (Exception e) {
4695 loge("Exception adding interface: " + e);
4696 }
4697 }
4698 for (String iface : interfaceDiff.removed) {
4699 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004700 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004701 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004702 mNetd.removeInterfaceFromNetwork(iface, netId);
4703 } catch (Exception e) {
4704 loge("Exception removing interface: " + e);
4705 }
4706 }
4707 }
4708
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004709 /**
4710 * Have netd update routes from oldLp to newLp.
4711 * @return true if routes changed between oldLp and newLp
4712 */
4713 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004714 // Compare the route diff to determine which routes should be added and removed.
4715 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4716 oldLp != null ? oldLp.getAllRoutes() : null,
4717 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004718
4719 // add routes before removing old in case it helps with continuous connectivity
4720
Chalard Jean4d660112018-06-04 16:52:49 +09004721 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004722 for (RouteInfo route : routeDiff.added) {
4723 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004724 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725 try {
4726 mNetd.addRoute(netId, route);
4727 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004728 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4729 loge("Exception in addRoute for non-gateway: " + e);
4730 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004731 }
4732 }
4733 for (RouteInfo route : routeDiff.added) {
4734 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004735 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004736 try {
4737 mNetd.addRoute(netId, route);
4738 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004739 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4740 loge("Exception in addRoute for gateway: " + e);
4741 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004742 }
4743 }
4744
4745 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004746 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004747 try {
4748 mNetd.removeRoute(netId, route);
4749 } catch (Exception e) {
4750 loge("Exception in removeRoute: " + e);
4751 }
4752 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004753 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 }
Erik Kline41368502015-06-17 13:19:54 +09004755
Erik Kline94887872016-04-05 13:30:49 +09004756 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4757 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4758 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 }
Erik Kline94887872016-04-05 13:30:49 +09004760
Erik Kline1742fe12017-12-13 19:40:49 +09004761 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4762 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4763
Erik Klinea24d4592018-01-11 21:07:29 +09004764 if (DBG) {
4765 final Collection<InetAddress> dnses = newLp.getDnsServers();
4766 log("Setting DNS servers for network " + netId + " to " + dnses);
4767 }
Erik Kline94887872016-04-05 13:30:49 +09004768 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004769 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004770 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004771 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004772 }
Erik Kline4edba012017-04-07 15:29:29 +09004773 }
4774
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004775 private String getNetworkPermission(NetworkCapabilities nc) {
4776 // TODO: make these permission strings AIDL constants instead.
4777 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4778 return NetworkManagementService.PERMISSION_SYSTEM;
4779 }
4780 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4781 return NetworkManagementService.PERMISSION_NETWORK;
4782 }
4783 return null;
4784 }
4785
Paul Jensen3d194ea2015-06-16 14:27:36 -04004786 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004787 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4788 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4789 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004790 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004791 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004792 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004793 // Don't complain for VPNs since they're not driven by requests and there is no risk of
4794 // causing a connect/teardown loop.
4795 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
4796 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004797 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004798 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004799 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4800 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004801 // does not cause any request (that is not a listen) currently matching that agent to
4802 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004803 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004804 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004805 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004806 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004807 }
4808
Paul Jensen3d194ea2015-06-16 14:27:36 -04004809 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004810 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004811 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004812 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004813 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004815 }
Paul Jensene0988542015-06-25 15:30:08 -04004816 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004817 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004818 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004820 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004821 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004822 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004824 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004826 if (nai.isSuspended()) {
4827 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4828 } else {
4829 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4830 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004831
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004832 return newNc;
4833 }
4834
4835 /**
4836 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4837 *
4838 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4839 * capabilities we manage and store in {@code nai}, such as validated status and captive
4840 * portal status)
4841 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4842 * potentially triggers rematches.
4843 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4844 * change.)
4845 *
4846 * @param oldScore score of the network before any of the changes that prompted us
4847 * to call this function.
4848 * @param nai the network having its capabilities updated.
4849 * @param nc the new network capabilities.
4850 */
4851 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4852 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4853
4854 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004855
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004856 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004857 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004858 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004859 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004860 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 } catch (RemoteException e) {
4862 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004863 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004864 }
4865
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004866 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004867 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004868 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004869 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004870 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004871
Chalard Jeanf213ca12018-01-16 18:43:05 +09004872 updateUids(nai, prevNc, newNc);
4873
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004874 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004875 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4876 // the change we're processing can't affect any requests, it can only affect the listens
4877 // on this network. We might have been called by rematchNetworkAndRequests when a
4878 // network changed foreground state.
4879 processListenRequests(nai, true);
4880 } else {
4881 // If the requestable capabilities have changed or the score changed, we can't have been
4882 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004883 rematchAllNetworksAndRequests(nai, oldScore);
4884 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004885 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004886
4887 // Report changes that are interesting for network statistics tracking.
4888 if (prevNc != null) {
4889 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004890 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004891 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004893 if (meteredChanged || roamingChanged) {
4894 notifyIfacesChangedForNetworkStats();
4895 }
4896 }
4897
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004898 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004899 // Tell VPNs about updated capabilities, since they may need to
4900 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004901 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004902 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004903 }
4904
Chalard Jeanf213ca12018-01-16 18:43:05 +09004905 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4906 NetworkCapabilities newNc) {
4907 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4908 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4909 if (null == prevRanges) prevRanges = new ArraySet<>();
4910 if (null == newRanges) newRanges = new ArraySet<>();
4911 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4912
4913 prevRanges.removeAll(newRanges);
4914 newRanges.removeAll(prevRangesCopy);
4915
4916 try {
4917 if (!newRanges.isEmpty()) {
4918 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4919 newRanges.toArray(addedRangesArray);
4920 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4921 }
4922 if (!prevRanges.isEmpty()) {
4923 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4924 prevRanges.toArray(removedRangesArray);
4925 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4926 }
4927 } catch (Exception e) {
4928 // Never crash!
4929 loge("Exception in updateUids: " + e);
4930 }
4931 }
4932
Hugo Benichief502882017-09-01 01:23:32 +00004933 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004934 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004935 // Ignore updates for disconnected networks
4936 return;
4937 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004938 // newLp is already a defensive copy.
4939 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004940 if (VDBG) {
4941 log("Update of LinkProperties for " + nai.name() +
4942 "; created=" + nai.created +
4943 "; everConnected=" + nai.everConnected);
4944 }
4945 LinkProperties oldLp = nai.linkProperties;
4946 synchronized (nai) {
4947 nai.linkProperties = newLp;
4948 }
4949 if (nai.everConnected) {
4950 updateLinkProperties(nai, oldLp);
4951 }
4952 }
4953
Paul Jensenc8b9a742014-09-30 15:37:41 -04004954 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004955 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4956 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004957 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004958 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004959 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4960 }
4961 }
4962
Robert Greenwalt7b816022014-04-18 15:25:25 -07004963 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4964 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004965 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004966 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4967 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 }
4969 }
4970
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004971 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4972 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004973 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004974 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004975 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4976 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004977 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004978 sendIntent(nri.mPendingIntent, intent);
4979 }
4980 // else not handled
4981 }
4982
4983 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4984 mPendingIntentWakeLock.acquire();
4985 try {
4986 if (DBG) log("Sending " + pendingIntent);
4987 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4988 } catch (PendingIntent.CanceledException e) {
4989 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4990 mPendingIntentWakeLock.release();
4991 releasePendingNetworkRequest(pendingIntent);
4992 }
4993 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4994 }
4995
4996 @Override
4997 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4998 String resultData, Bundle resultExtras) {
4999 if (DBG) log("Finished sending " + pendingIntent);
5000 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005001 // Release with a delay so the receiving client has an opportunity to put in its
5002 // own request.
5003 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005004 }
5005
Chalard Jeanf19db372018-01-26 19:24:40 +09005006 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005007 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005008 if (nri.messenger == null) {
5009 return; // Default request has no msgr
5010 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005011 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005012 // TODO: check if defensive copies of data is needed.
5013 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005014 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005015 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5016 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005017 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005018 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005019 case ConnectivityManager.CALLBACK_AVAILABLE: {
5020 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5021 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5022 break;
5023 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005024 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005025 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005026 break;
5027 }
5028 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005029 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005030 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005031 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005032 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005033 break;
5034 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005035 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005036 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005037 break;
5038 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005039 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005040 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005041 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005042 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005043 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005044 String notification = ConnectivityManager.getCallbackName(notificationType);
5045 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005046 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005047 nri.messenger.send(msg);
5048 } catch (RemoteException e) {
5049 // may occur naturally in the race of binder death.
5050 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5051 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005052 }
5053
Hugo Benichidba33db2017-03-23 22:40:44 +09005054 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5055 bundle.putParcelable(t.getClass().getSimpleName(), t);
5056 }
5057
Paul Jensenc8b9a742014-09-30 15:37:41 -04005058 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005059 if (nai.numRequestNetworkRequests() != 0) {
5060 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5061 NetworkRequest nr = nai.requestAt(i);
5062 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005063 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005064 loge("Dead network still had at least " + nr);
5065 break;
5066 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005067 }
5068 nai.asyncChannel.disconnect();
5069 }
5070
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5072 if (oldNetwork == null) {
5073 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5074 return;
5075 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005076 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005077
5078 // If we get here it means that the last linger timeout for this network expired. So there
5079 // must be no other active linger timers, and we must stop lingering.
5080 oldNetwork.clearLingerState();
5081
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005082 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005083 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005084 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005085 } else {
5086 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005087 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5088 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005089 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005090 }
5091
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005092 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005093 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005094 setupDataActivityTracking(newNetwork);
5095 try {
5096 mNetd.setDefaultNetId(newNetwork.network.netId);
5097 } catch (Exception e) {
5098 loge("Exception setting default network :" + e);
5099 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005100
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005101 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005102 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005103 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005104 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005105 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005106 }
5107
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005108 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005109 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5110 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5111 NetworkRequest nr = nri.request;
5112 if (!nr.isListen()) continue;
5113 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5114 nai.removeRequest(nri.request.requestId);
5115 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5116 }
5117 }
5118
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005119 if (capabilitiesChanged) {
5120 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5121 }
5122
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005123 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5124 NetworkRequest nr = nri.request;
5125 if (!nr.isListen()) continue;
5126 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5127 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005128 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005129 }
5130 }
5131 }
5132
Paul Jensen2161a8e2014-09-11 11:00:39 -04005133 // Handles a network appearing or improving its score.
5134 //
5135 // - Evaluates all current NetworkRequests that can be
5136 // satisfied by newNetwork, and reassigns to newNetwork
5137 // any such requests for which newNetwork is the best.
5138 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005139 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005140 // needed. A network is needed if it is the best network for
5141 // one or more NetworkRequests, or if it is a VPN.
5142 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005143 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005144 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005145 //
5146 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5147 // networks that have no chance (i.e. even if validated)
5148 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005149 //
5150 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5151 // it does not remove NetworkRequests that other Networks could better satisfy.
5152 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5153 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5154 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005155 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005156 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005157 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5158 // performed to tear down unvalidated networks that have no chance (i.e. even if
5159 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005160 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005161 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005162 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005163 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005164 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005165 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005166
5167 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5168 final int score = newNetwork.getCurrentScore();
5169
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005170 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005171
Paul Jensen2161a8e2014-09-11 11:00:39 -04005172 // Find and migrate to this Network any NetworkRequests for
5173 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005174 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5175 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005176 NetworkCapabilities nc = newNetwork.networkCapabilities;
5177 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005178 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005179 // Process requests in the first pass and listens in the second pass. This allows us to
5180 // change a network's capabilities depending on which requests it has. This is only
5181 // correct if the change in capabilities doesn't affect whether the network satisfies
5182 // requests or not, and doesn't affect the network's score.
5183 if (nri.request.isListen()) continue;
5184
Hugo Benichicd952782017-09-20 11:20:14 +09005185 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005186 final boolean satisfies = newNetwork.satisfies(nri.request);
5187 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005188 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005189 log("Network " + newNetwork.name() + " was already satisfying" +
5190 " request " + nri.request.requestId + ". No change.");
5191 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005192 keep = true;
5193 continue;
5194 }
5195
5196 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005197 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005198 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005199 // next check if it's better than any current network we're using for
5200 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 if (VDBG) {
5202 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005203 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005204 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005205 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005206 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005207 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005208 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005209 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005210 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005211 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005212 affectedNetworks.add(currentNetwork);
5213 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005214 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005216 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005217 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005218 if (!newNetwork.addRequest(nri.request)) {
5219 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5220 }
5221 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005223 // Tell NetworkFactories about the new score, so they can stop
5224 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005225 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005226 // network. Think about if there is a way to reduce this. Push
5227 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005228 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005229 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005230 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005231 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005232 if (currentNetwork != null) {
5233 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5234 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005235 }
5236 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005237 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005238 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5239 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005240 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005241 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5242 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5243 // This means this code doesn't have to handle the case where "currentNetwork" no
5244 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5245 if (DBG) {
5246 log("Network " + newNetwork.name() + " stopped satisfying" +
5247 " request " + nri.request.requestId);
5248 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005249 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005250 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005251 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005252 sendUpdatedScoreToFactories(nri.request, 0);
5253 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005254 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5255 newNetwork.name() +
5256 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005257 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005258 // TODO: Technically, sending CALLBACK_LOST here is
5259 // incorrect if there is a replacement network currently
5260 // connected that can satisfy nri, which is a request
5261 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005262 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5263 // so this code is only incorrect for a network that loses
5264 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005265 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005266 }
5267 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005268 if (isNewDefault) {
5269 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005270 makeDefault(newNetwork);
5271 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005272 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005273 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005274 // Have a new default network, release the transition wakelock in
5275 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005276 }
5277
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005278 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5279 Slog.wtf(TAG, String.format(
5280 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005281 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005282 }
5283 if (newNetwork.getCurrentScore() != score) {
5284 Slog.wtf(TAG, String.format(
5285 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005286 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005287 }
5288
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005289 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005290 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5291 // If the network went from background to foreground or vice versa, we need to update
5292 // its foreground state. It is safe to do this after rematching the requests because
5293 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5294 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005295 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005296 } else {
5297 processListenRequests(newNetwork, false);
5298 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005299
Paul Jensencf4c2c62015-07-01 14:16:32 -04005300 // do this after the default net is switched, but
5301 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005302 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005303
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005304 // Linger any networks that are no longer needed. This should be done after sending the
5305 // available callback for newNetwork.
5306 for (NetworkAgentInfo nai : affectedNetworks) {
5307 updateLingerState(nai, now);
5308 }
5309 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5310 // does not need to be done in any particular order.
5311 updateLingerState(newNetwork, now);
5312
Paul Jensencf4c2c62015-07-01 14:16:32 -04005313 if (isNewDefault) {
5314 // Maintain the illusion: since the legacy API only
5315 // understands one network at a time, we must pretend
5316 // that the current default network disconnected before
5317 // the new one connected.
5318 if (oldDefaultNetwork != null) {
5319 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5320 oldDefaultNetwork, true);
5321 }
5322 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5323 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5324 notifyLockdownVpn(newNetwork);
5325 }
5326
Robert Greenwalt7b816022014-04-18 15:25:25 -07005327 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005328 // Notify battery stats service about this network, both the normal
5329 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005330 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005331 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005332 final IBatteryStats bs = BatteryStatsService.getService();
5333 final int type = newNetwork.networkInfo.getType();
5334
5335 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5336 bs.noteNetworkInterfaceType(baseIface, type);
5337 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5338 final String stackedIface = stacked.getInterfaceName();
5339 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005340 }
5341 } catch (RemoteException ignored) {
5342 }
5343
Robert Greenwalt152ed372014-12-17 17:19:53 -08005344 // This has to happen after the notifyNetworkCallbacks as that tickles each
5345 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005346 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005347 // and will generally do a dns request so they can ensureRouteToHost and if
5348 // they do that before the callbacks happen they'll use the default network.
5349 //
5350 // TODO: Is there still a race here? We send the broadcast
5351 // after sending the callback, but if the app can receive the
5352 // broadcast before the callback, it might still break.
5353 //
5354 // This *does* introduce a race where if the user uses the new api
5355 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5356 // they may get old info. Reverse this after the old startUsing api is removed.
5357 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005358 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5359 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005360 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005361 // legacy type tracker filters out repeat adds
5362 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5363 }
5364 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005365
5366 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5367 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5368 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5369 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5370 if (newNetwork.isVPN()) {
5371 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5372 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005373 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005374 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5375 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005376 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005377 if (nai.getLingerExpiry() > 0) {
5378 // This network has active linger timers and no requests, but is not
5379 // lingering. Linger it.
5380 //
5381 // One way (the only way?) this can happen if this network is unvalidated
5382 // and became unneeded due to another network improving its score to the
5383 // point where this network will no longer be able to satisfy any requests
5384 // even if it validates.
5385 updateLingerState(nai, now);
5386 } else {
5387 if (DBG) log("Reaping " + nai.name());
5388 teardownUnneededNetwork(nai);
5389 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005390 }
5391 }
5392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005393 }
5394
Paul Jensen1c7ba022015-06-16 14:27:36 -04005395 /**
5396 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5397 * being disconnected.
5398 * @param changed If only one Network's score or capabilities have been modified since the last
5399 * time this function was called, pass this Network in this argument, otherwise pass
5400 * null.
5401 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5402 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5403 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5404 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5405 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005406 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005407 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005408 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5409 // to avoid the slowness. It is not simply enough to process just "changed", for
5410 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005411 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005412
5413 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5414 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5415 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005416 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005417 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005418 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005419 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005420 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5421 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5422 // Rematch higher scoring networks first to prevent requests first matching a lower
5423 // scoring network and then a higher scoring network, which could produce multiple
5424 // callbacks and inadvertently unlinger networks.
5425 Arrays.sort(nais);
5426 for (NetworkAgentInfo nai : nais) {
5427 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005428 // Only reap the last time through the loop. Reaping before all rematching
5429 // is complete could incorrectly teardown a network that hasn't yet been
5430 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005431 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005432 : ReapUnvalidatedNetworks.REAP,
5433 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005434 }
5435 }
5436 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005437
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005438 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005439 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005440 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005441 // For now only update icons for default connection.
5442 // TODO: Update WiFi and cellular icons separately. b/17237507
5443 if (!isDefaultNetwork(nai)) return;
5444
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005445 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005446 // Don't repeat publish.
5447 if (newInetCondition == mDefaultInetConditionPublished) return;
5448
5449 mDefaultInetConditionPublished = newInetCondition;
5450 sendInetConditionBroadcast(nai.networkInfo);
5451 }
5452
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005453 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005454 synchronized (mVpns) {
5455 if (mLockdownTracker != null) {
5456 if (nai != null && nai.isVPN()) {
5457 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5458 } else {
5459 mLockdownTracker.onNetworkInfoChanged();
5460 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005461 }
5462 }
5463 }
5464
Robert Greenwalt7b816022014-04-18 15:25:25 -07005465 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005466 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005467 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005468 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005469 synchronized (networkAgent) {
5470 oldInfo = networkAgent.networkInfo;
5471 networkAgent.networkInfo = newInfo;
5472 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005473 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005474
Robert Greenwalt7b816022014-04-18 15:25:25 -07005475 if (DBG) {
5476 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5477 (oldInfo == null ? "null" : oldInfo.getState()) +
5478 " to " + state);
5479 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005480
Robin Lee585e2482016-05-01 23:00:00 +01005481 if (!networkAgent.created
5482 && (state == NetworkInfo.State.CONNECTED
5483 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005484
5485 // A network that has just connected has zero requests and is thus a foreground network.
5486 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5487
Robert Greenwalt7b816022014-04-18 15:25:25 -07005488 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005489 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005490 if (networkAgent.isVPN()) {
5491 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005492 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5493 (networkAgent.networkMisc == null ||
5494 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005495 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005496 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005497 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005498 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005499 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005500 loge("Error creating network " + networkAgent.network.netId + ": "
5501 + e.getMessage());
5502 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005503 }
Paul Jenseneec75412014-08-04 12:21:19 -04005504 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005505 }
5506
5507 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5508 networkAgent.everConnected = true;
5509
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005510 if (networkAgent.linkProperties == null) {
5511 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5512 }
5513
Erik Kline736353a2018-03-21 07:18:33 -07005514 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005515 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005516
Paul Jensenca8f16a2014-05-09 12:47:55 -04005517 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005518 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005519
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005520 if (networkAgent.isVPN()) {
5521 // Temporarily disable the default proxy (not global).
Chalard Jean52c2aa72018-06-07 16:44:04 +09005522 synchronized (mProxyTracker.mProxyLock) {
5523 if (!mProxyTracker.mDefaultProxyDisabled) {
5524 mProxyTracker.mDefaultProxyDisabled = true;
5525 if (mProxyTracker.mGlobalProxy == null
5526 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005527 mProxyTracker.sendProxyBroadcast(null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005528 }
5529 }
5530 }
5531 // TODO: support proxy per network.
5532 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005533
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005534 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5535 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5536 // capabilities, so it only needs to be done once on initial connect, not every time the
5537 // network's capabilities change. Note that we do this before rematching the network,
5538 // so we could decide to tear it down immediately afterwards. That's fine though - on
5539 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5540 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005541 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005542
Paul Jensen2161a8e2014-09-11 11:00:39 -04005543 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005544 final long now = SystemClock.elapsedRealtime();
5545 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005546
5547 // This has to happen after matching the requests, because callbacks are just requests.
5548 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005549 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005550 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005551 if (networkAgent.isVPN()) {
Chalard Jean52c2aa72018-06-07 16:44:04 +09005552 synchronized (mProxyTracker.mProxyLock) {
5553 if (mProxyTracker.mDefaultProxyDisabled) {
5554 mProxyTracker.mDefaultProxyDisabled = false;
5555 if (mProxyTracker.mGlobalProxy == null
5556 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005557 mProxyTracker.sendProxyBroadcast(mProxyTracker.mDefaultProxy);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005558 }
5559 }
5560 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005561 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005562 }
Chalard Jean392971c2018-05-11 20:19:20 +09005563 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005564 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5565 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005566 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005567 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005568 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005569 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005570 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5571 networkAgent.networkCapabilities);
5572 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5573 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005574 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5575 ConnectivityManager.CALLBACK_SUSPENDED :
5576 ConnectivityManager.CALLBACK_RESUMED));
5577 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005578 }
5579 }
5580
Robert Greenwaltac96c522014-06-03 16:43:57 -07005581 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005582 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005583 if (score < 0) {
5584 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5585 "). Bumping score to min of 0");
5586 score = 0;
5587 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005588
Paul Jensen2161a8e2014-09-11 11:00:39 -04005589 final int oldScore = nai.getCurrentScore();
5590 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005591
Paul Jensen85cf78e2015-06-25 13:25:07 -04005592 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005593
Paul Jensenc8b9a742014-09-30 15:37:41 -04005594 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005595 }
5596
Erik Klinec75d4fa2017-02-15 19:59:17 +09005597 // Notify only this one new request of the current state. Transfer all the
5598 // current state by calling NetworkCapabilities and LinkProperties callbacks
5599 // so that callers can be guaranteed to have as close to atomicity in state
5600 // transfer as can be supported by this current API.
5601 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005602 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005603 if (nri.mPendingIntent != null) {
5604 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5605 // Attempt no subsequent state pushes where intents are involved.
5606 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005607 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005608
5609 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005610 }
5611
Robert Greenwalt8d482522015-06-24 13:23:42 -07005612 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005613 // The NetworkInfo we actually send out has no bearing on the real
5614 // state of affairs. For example, if the default connection is mobile,
5615 // and a request for HIPRI has just gone away, we need to pretend that
5616 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5617 // the state to DISCONNECTED, even though the network is of type MOBILE
5618 // and is still connected.
5619 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5620 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005621 if (state != DetailedState.DISCONNECTED) {
5622 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005623 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005624 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005625 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005626 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5627 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5628 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5629 if (info.isFailover()) {
5630 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5631 nai.networkInfo.setFailover(false);
5632 }
5633 if (info.getReason() != null) {
5634 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5635 }
5636 if (info.getExtraInfo() != null) {
5637 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5638 }
5639 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005640 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005641 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005642 if (newDefaultAgent != null) {
5643 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5644 newDefaultAgent.networkInfo);
5645 } else {
5646 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5647 }
5648 }
5649 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5650 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005651 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005652 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005653 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005654 }
5655 }
5656 }
5657
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005658 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005659 if (VDBG) {
5660 String notification = ConnectivityManager.getCallbackName(notifyType);
5661 log("notifyType " + notification + " for " + networkAgent.name());
5662 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005663 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5664 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005665 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5666 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005667 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5668 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005669 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005670 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005671 } else {
5672 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5673 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005674 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005675 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005676
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005677 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5678 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5679 }
5680
Jeff Sharkey69736342014-12-08 14:50:12 -08005681 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005682 * Returns the list of all interfaces that could be used by network traffic that does not
5683 * explicitly specify a network. This includes the default network, but also all VPNs that are
5684 * currently connected.
5685 *
5686 * Must be called on the handler thread.
5687 */
5688 private Network[] getDefaultNetworks() {
5689 ArrayList<Network> defaultNetworks = new ArrayList<>();
5690 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5691 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5692 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5693 defaultNetworks.add(nai.network);
5694 }
5695 }
5696 return defaultNetworks.toArray(new Network[0]);
5697 }
5698
5699 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005700 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5701 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005702 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005703 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005704 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005705 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005706 } catch (Exception ignored) {
5707 }
5708 }
5709
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005710 @Override
5711 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005712 int user = UserHandle.getUserId(Binder.getCallingUid());
5713 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005714 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005715 return mVpns.get(user).addAddress(address, prefixLength);
5716 }
5717 }
5718
5719 @Override
5720 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005721 int user = UserHandle.getUserId(Binder.getCallingUid());
5722 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005723 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005724 return mVpns.get(user).removeAddress(address, prefixLength);
5725 }
5726 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005727
5728 @Override
5729 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005730 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005731 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005732 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005733 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005734 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005735 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005736 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005737 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005738 }
5739 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005740 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005741
5742 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005743 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005744 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005745 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005746 }
5747
5748 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005749 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5750 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5751 enforceKeepalivePermission();
5752 mKeepaliveTracker.startNattKeepalive(
5753 getNetworkAgentInfoForNetwork(network),
5754 intervalSeconds, messenger, binder,
5755 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5756 }
5757
5758 @Override
5759 public void stopKeepalive(Network network, int slot) {
5760 mHandler.sendMessage(mHandler.obtainMessage(
5761 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5762 }
5763
5764 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005765 public void factoryReset() {
5766 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005767
5768 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5769 return;
5770 }
5771
Robin Lee3b3dd942015-05-12 18:14:58 +01005772 final int userId = UserHandle.getCallingUserId();
5773
Stuart Scottf1fb3972015-04-02 18:00:02 -07005774 // Turn airplane mode off
5775 setAirplaneMode(false);
5776
Stuart Scotte3e314d2015-04-20 14:07:45 -07005777 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5778 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005779 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005780 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005781 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005782 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005783 }
5784
Stuart Scotte3e314d2015-04-20 14:07:45 -07005785 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005786 // Remove always-on package
5787 synchronized (mVpns) {
5788 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5789 if (alwaysOnPackage != null) {
5790 setAlwaysOnVpnPackage(userId, null, false);
5791 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5792 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005793
Hugo Benichi69744342017-11-27 10:57:16 +09005794 // Turn Always-on VPN off
5795 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5796 final long ident = Binder.clearCallingIdentity();
5797 try {
5798 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5799 mLockdownEnabled = false;
5800 setLockdownTracker(null);
5801 } finally {
5802 Binder.restoreCallingIdentity(ident);
5803 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005804 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005805
Hugo Benichi69744342017-11-27 10:57:16 +09005806 // Turn VPN off
5807 VpnConfig vpnConfig = getVpnConfig(userId);
5808 if (vpnConfig != null) {
5809 if (vpnConfig.legacy) {
5810 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5811 } else {
5812 // Prevent this app (packagename = vpnConfig.user) from initiating
5813 // VPN connections in the future without user intervention.
5814 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005815
Hugo Benichi69744342017-11-27 10:57:16 +09005816 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5817 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005818 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005819 }
5820 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005821
5822 Settings.Global.putString(mContext.getContentResolver(),
5823 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005824 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005825
Ricky Wai44dcbde2018-01-23 04:09:45 +00005826 @Override
5827 public byte[] getNetworkWatchlistConfigHash() {
5828 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5829 if (nwm == null) {
5830 loge("Unable to get NetworkWatchlistManager");
5831 return null;
5832 }
5833 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5834 return nwm.getWatchlistConfigHash();
5835 }
5836
Paul Jensencf4c2c62015-07-01 14:16:32 -04005837 @VisibleForTesting
5838 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5839 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5840 return new NetworkMonitor(context, handler, nai, defaultRequest);
5841 }
Erik Kline48f12f22016-04-14 17:30:59 +09005842
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005843 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005844 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5845 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005846 }
5847
5848 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005849 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5850 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5851 }
5852
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005853 @VisibleForTesting
5854 public boolean hasService(String name) {
5855 return ServiceManager.checkService(name) != null;
5856 }
5857
Hugo Benichi64901e52017-10-19 14:42:40 +09005858 @VisibleForTesting
5859 protected IpConnectivityMetrics.Logger metricsLogger() {
5860 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5861 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005862 }
5863
5864 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005865 int[] transports = nai.networkCapabilities.getTransportTypes();
5866 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005867 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005868
5869 private static boolean toBool(int encodedBoolean) {
5870 return encodedBoolean != 0; // Only 0 means false.
5871 }
5872
5873 private static int encodeBool(boolean b) {
5874 return b ? 1 : 0;
5875 }
mswest46386886f2018-03-12 10:34:34 -07005876
5877 @Override
5878 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5879 FileDescriptor err, String[] args, ShellCallback callback,
5880 ResultReceiver resultReceiver) {
5881 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5882 }
5883
5884 private class ShellCmd extends ShellCommand {
5885
5886 @Override
5887 public int onCommand(String cmd) {
5888 if (cmd == null) {
5889 return handleDefaultCommands(cmd);
5890 }
5891 final PrintWriter pw = getOutPrintWriter();
5892 try {
5893 switch (cmd) {
5894 case "airplane-mode":
5895 final String action = getNextArg();
5896 if ("enable".equals(action)) {
5897 setAirplaneMode(true);
5898 return 0;
5899 } else if ("disable".equals(action)) {
5900 setAirplaneMode(false);
5901 return 0;
5902 } else if (action == null) {
5903 final ContentResolver cr = mContext.getContentResolver();
5904 final int enabled = Settings.Global.getInt(cr,
5905 Settings.Global.AIRPLANE_MODE_ON);
5906 pw.println(enabled == 0 ? "disabled" : "enabled");
5907 return 0;
5908 } else {
5909 onHelp();
5910 return -1;
5911 }
5912 default:
5913 return handleDefaultCommands(cmd);
5914 }
5915 } catch (Exception e) {
5916 pw.println(e);
5917 }
5918 return -1;
5919 }
5920
5921 @Override
5922 public void onHelp() {
5923 PrintWriter pw = getOutPrintWriter();
5924 pw.println("Connectivity service commands:");
5925 pw.println(" help");
5926 pw.println(" Print this help text.");
5927 pw.println(" airplane-mode [enable|disable]");
5928 pw.println(" Turn airplane mode on or off.");
5929 pw.println(" airplane-mode");
5930 pw.println(" Get airplane mode.");
5931 }
5932 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07005933
5934 /**
5935 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
5936 * for testing.
5937 */
5938 private Vpn enforceActiveVpnOrNetworkStackPermission() {
5939 if (checkNetworkStackPermission()) {
5940 return null;
5941 }
5942 final int uid = Binder.getCallingUid();
5943 final int user = UserHandle.getUserId(uid);
5944 synchronized (mVpns) {
5945 Vpn vpn = mVpns.get(user);
5946 try {
5947 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
5948 } catch (NullPointerException e) {
5949 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
5950 }
5951 }
5952 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
5953 + "permission");
5954 }
5955
5956 /**
5957 * @param connectionInfo the connection to resolve.
5958 * @return {@code uid} if the connection is found and the app has permission to observe it
5959 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
5960 * connection is not found.
5961 */
5962 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
5963 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
5964 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
5965 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
5966 }
5967
5968 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
5969 connectionInfo.local, connectionInfo.remote);
5970
5971 /* Filter out Uids not associated with the VPN. */
5972 if (vpn != null && !vpn.appliesToUid(uid)) {
5973 return INVALID_UID;
5974 }
5975
5976 return uid;
5977 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005978}