blob: 2c5327b9be37b0ceff6186838f218e0d0973b697 [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 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700393 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900394 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700395 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900396
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
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700751 // The default WiFi request is a background request so that apps using WiFi are
752 // migrated to a better network (typically ethernet) when one comes up, instead
753 // of staying on WiFi forever.
754 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
755 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
756
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900757 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900758 mHandlerThread.start();
759 mHandler = new InternalHandler(mHandlerThread.getLooper());
760 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700761
Jeremy Joslin79294842014-12-03 17:15:28 -0800762 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
763 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
764
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900765 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900766
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700767 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700768 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800769 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700770 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900771 mPolicyManagerInternal = checkNotNull(
772 LocalServices.getService(NetworkPolicyManagerInternal.class),
773 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900774 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900775
Jeff Sharkey82f85212012-08-24 11:17:25 -0700776 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700777 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700778
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700779 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900780 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700781 } catch (RemoteException e) {
782 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700783 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700784 }
785
786 final PowerManager powerManager = (PowerManager) context.getSystemService(
787 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700788 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
789 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
790 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800791 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700792
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700793 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700794
Wink Saville51f456f2013-04-23 14:26:51 -0700795 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900796 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700797 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700798 String[] naStrings = context.getResources().getStringArray(
799 com.android.internal.R.array.networkAttributes);
800 for (String naString : naStrings) {
801 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700802 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700803 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700804 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800805 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700806 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700807 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700808 }
Wink Saville51f456f2013-04-23 14:26:51 -0700809 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
810 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
811 n.type);
812 continue;
813 }
Wink Saville975c8482011-04-07 14:23:45 -0700814 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800815 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700816 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700817 continue;
818 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700819 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700820
Wink Saville975c8482011-04-07 14:23:45 -0700821 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700822 mNetworksDefined++;
823 } catch(Exception e) {
824 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700825 }
826 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700827
828 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
829 if (mNetConfigs[TYPE_VPN] == null) {
830 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
831 // don't need to add TYPE_VPN to mNetConfigs.
832 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
833 mNetworksDefined++; // used only in the log() statement below.
834 }
835
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900836 // Do the same for Ethernet, since it's often not specified in the configs, although many
837 // devices can use it via USB host adapters.
838 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
839 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
840 mNetworksDefined++;
841 }
842
Wink Saville5e56bc52013-07-29 15:00:57 -0700843 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700844
Robert Greenwalt50393202011-06-21 17:26:14 -0700845 mProtectedNetworks = new ArrayList<Integer>();
846 int[] protectedNetworks = context.getResources().getIntArray(
847 com.android.internal.R.array.config_protectedNetworks);
848 for (int p : protectedNetworks) {
849 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
850 mProtectedNetworks.add(p);
851 } else {
852 if (DBG) loge("Ignoring protectedNetwork " + p);
853 }
854 }
855
Erik Kline47222fc2017-04-30 19:36:15 +0900856 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800857
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700858 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
859
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700860 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700861 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100862 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700863 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700864 intentFilter.addAction(Intent.ACTION_USER_ADDED);
865 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000866 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700867 mContext.registerReceiverAsUser(
868 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000869 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
870 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900871
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700872 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700873 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700874 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700875 } catch (RemoteException e) {
876 loge("Error registering observer :" + e);
877 }
878
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 mSettingsObserver = new SettingsObserver(mContext, mHandler);
880 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800881
Chalard Jean4133a122018-06-04 13:33:12 +0900882 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
883 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400884
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400885 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900886
887 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900888 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
889 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900890
891 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
892 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
893 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
894 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
895 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
896 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
897 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900898
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900899 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900900 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900901 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900902
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900903 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
904
Erik Kline1742fe12017-12-13 19:40:49 +0900905 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900906 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700908
Erik Kline47222fc2017-04-30 19:36:15 +0900909 private Tethering makeTethering() {
910 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900911 final TetheringDependencies deps = new TetheringDependencies() {
912 @Override
913 public boolean isTetheringSupported() {
914 return ConnectivityService.this.isTetheringSupported();
915 }
Erik Kline72302902018-06-14 17:36:40 +0900916 @Override
917 public NetworkRequest getDefaultNetworkRequest() {
918 return mDefaultRequest;
919 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900920 };
Erik Kline47222fc2017-04-30 19:36:15 +0900921 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
922 IoThread.get().getLooper(), new MockableSystemProperties(),
923 deps);
924 }
925
Chalard Jean26400492018-04-18 20:18:38 +0900926 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
927 final NetworkCapabilities netCap = new NetworkCapabilities();
928 netCap.addCapability(NET_CAPABILITY_INTERNET);
929 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
930 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
931 netCap.setSingleUid(uid);
932 return netCap;
933 }
934
Chalard Jeandda156a2018-01-10 21:19:32 +0900935 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900936 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900937 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900938 netCap.addCapability(NET_CAPABILITY_INTERNET);
939 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900940 if (transportType > -1) {
941 netCap.addTransportType(transportType);
942 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900943 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900944 }
945
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900946 // Used only for testing.
947 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700948 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900949 // changing ContentResolver to make registerContentObserver non-final).
950 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
951 // by subclassing SettingsObserver.
952 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700953 void updateAlwaysOnNetworks() {
954 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900955 }
956
Erik Kline736353a2018-03-21 07:18:33 -0700957 // See FakeSettingsProvider comment above.
958 @VisibleForTesting
959 void updatePrivateDnsSettings() {
960 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
961 }
962
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700963 private void handleAlwaysOnNetworkRequest(
964 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900965 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700966 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
967 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +0900968 if (enable == isEnabled) {
969 return; // Nothing to do.
970 }
971
972 if (enable) {
973 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700974 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900975 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700976 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +0900977 }
978 }
979
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700980 private void handleConfigureAlwaysOnNetworks() {
981 handleAlwaysOnNetworkRequest(
982 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
983 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
984 false);
985 }
986
Erik Klineda4bfa82015-04-30 12:58:40 +0900987 private void registerSettingsCallbacks() {
988 // Watch for global HTTP proxy changes.
989 mSettingsObserver.observe(
990 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
991 EVENT_APPLY_GLOBAL_HTTP_PROXY);
992
993 // Watch for whether or not to keep mobile data always on.
994 mSettingsObserver.observe(
995 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700996 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
997
998 // Watch for whether or not to keep wifi always on.
999 mSettingsObserver.observe(
1000 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1001 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001002 }
1003
Erik Klinea24d4592018-01-11 21:07:29 +09001004 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001005 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1006 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001007 }
1008 }
1009
Robert Greenwalt34524f02014-05-18 16:22:10 -07001010 private synchronized int nextNetworkRequestId() {
1011 return mNextNetworkRequestId++;
1012 }
1013
Paul Jensen67b0b072015-06-10 11:22:17 -04001014 @VisibleForTesting
1015 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001016 synchronized (mNetworkForNetId) {
1017 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1018 int netId = mNextNetId;
1019 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1020 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001021 if (!mNetIdInUse.get(netId)) {
1022 mNetIdInUse.put(netId, true);
1023 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001024 }
1025 }
1026 }
1027 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001028 }
1029
Chalard Jeanc0982912018-06-07 16:11:34 +09001030 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001032 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1033 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001035 state = nai.getNetworkState();
1036 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001038 final NetworkInfo info = new NetworkInfo(networkType, 0,
1039 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1041 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001042 final NetworkCapabilities capabilities = new NetworkCapabilities();
1043 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1044 !info.isRoaming());
1045 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001046 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001048 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001049 return state;
1050 } else {
1051 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001053 }
1054
junyulai4a192e22018-06-13 15:00:37 +08001055 @VisibleForTesting
1056 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 if (network == null) {
1058 return null;
1059 }
Erik Kline736353a2018-03-21 07:18:33 -07001060 return getNetworkAgentInfoForNetId(network.netId);
1061 }
1062
1063 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001064 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001065 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001069 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001070 synchronized (mVpns) {
1071 if (!mLockdownEnabled) {
1072 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001073 Vpn vpn = mVpns.get(user);
1074 if (vpn != null && vpn.appliesToUid(uid)) {
1075 return vpn.getUnderlyingNetworks();
1076 }
1077 }
1078 }
1079 return null;
1080 }
1081
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001082 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001083 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001084
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001085 final Network[] networks = getVpnUnderlyingNetworks(uid);
1086 if (networks != null) {
1087 // getUnderlyingNetworks() returns:
1088 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1089 // empty array => the VPN explicitly said "no default network".
1090 // non-empty array => the VPN specified one or more default networks; we use the
1091 // first one.
1092 if (networks.length > 0) {
1093 nai = getNetworkAgentInfoForNetwork(networks[0]);
1094 } else {
1095 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001096 }
1097 }
1098
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001099 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001100 return nai.getNetworkState();
1101 } else {
1102 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001103 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001104 }
1105
1106 /**
1107 * Check if UID should be blocked from using the network with the given LinkProperties.
1108 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1110 boolean ignoreBlocked) {
1111 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001112 if (ignoreBlocked) {
1113 return false;
1114 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001116 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1117 if (isSystem(uid)) {
1118 return false;
1119 }
Robin Lee17e61832016-05-09 13:46:28 +01001120 synchronized (mVpns) {
1121 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1122 if (vpn != null && vpn.isBlockingUid(uid)) {
1123 return true;
1124 }
1125 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001126 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001127 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001128 }
1129
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001130 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001131 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1132 return;
1133 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001134 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001135 synchronized (mBlockedAppUids) {
1136 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001137 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001138 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001139 blocked = false;
1140 } else {
1141 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001142 }
1143 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001144 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1145 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1146 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001147 }
1148
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001150 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1151 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001152 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001154 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001155 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1156
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001157 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 }
Hugo Benichi69744342017-11-27 10:57:16 +09001160 synchronized (mVpns) {
1161 if (mLockdownTracker != null) {
1162 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1163 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001164 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 }
1166
1167 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 * Return NetworkInfo for the active (i.e., connected) network interface.
1169 * It is assumed that at most one network is active at a time. If more
1170 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001171 * @return the info for the active network, or {@code null} if none is
1172 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001176 enforceAccessPermission();
1177 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1181 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183
Paul Jensen31a94f42015-02-13 14:18:39 -05001184 @Override
1185 public Network getActiveNetwork() {
1186 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001188 }
1189
1190 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001192 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001193 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001194 }
1195
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001196 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001197 final int user = UserHandle.getUserId(uid);
1198 int vpnNetId = NETID_UNSET;
1199 synchronized (mVpns) {
1200 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001201 // TODO : now that capabilities contain the UID, the appliesToUid test should
1202 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001203 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1204 }
1205 NetworkAgentInfo nai;
1206 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001207 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001208 if (nai != null) {
1209 final NetworkCapabilities requiredCaps =
1210 createDefaultNetworkCapabilitiesForUid(uid);
1211 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1212 return nai.network;
1213 }
1214 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001215 }
1216 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001217 if (nai != null
1218 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1219 nai = null;
1220 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001221 return nai != null ? nai.network : null;
1222 }
1223
Lorenzo Colitti18660282016-07-04 12:55:44 +09001224 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001225 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1226 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 final int uid = Binder.getCallingUid();
1228 NetworkState state = getUnfilteredActiveNetworkState(uid);
1229 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001230 }
1231
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001233 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001234 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001235 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001236 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001237 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001238 }
1239
1240 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 public NetworkInfo getNetworkInfo(int networkType) {
1242 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001244 if (getVpnUnderlyingNetworks(uid) != null) {
1245 // A VPN is active, so we may need to return one of its underlying networks. This
1246 // information is not available in LegacyTypeTracker, so we have to get it from
1247 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001248 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001249 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001250 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001251 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001252 }
1253 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001254 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001259 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001260 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001261 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001263 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001264 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001265 return state.networkInfo;
1266 } else {
1267 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001269 }
1270
1271 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 public NetworkInfo[] getAllNetworkInfo() {
1273 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001274 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001275 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1276 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001277 NetworkInfo info = getNetworkInfo(networkType);
1278 if (info != null) {
1279 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001282 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 }
1284
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001285 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001286 public Network getNetworkForType(int networkType) {
1287 enforceAccessPermission();
1288 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001289 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001290 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001292 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001293 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001294 }
1295
1296 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001297 public Network[] getAllNetworks() {
1298 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001299 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001300 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001302 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001303 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001304 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 }
1307
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001308 @Override
1309 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1310 // The basic principle is: if an app's traffic could possibly go over a
1311 // network, without the app doing anything multinetwork-specific,
1312 // (hence, by "default"), then include that network's capabilities in
1313 // the array.
1314 //
1315 // In the normal case, app traffic only goes over the system's default
1316 // network connection, so that's the only network returned.
1317 //
1318 // With a VPN in force, some app traffic may go into the VPN, and thus
1319 // over whatever underlying networks the VPN specifies, while other app
1320 // traffic may go over the system default network (e.g.: a split-tunnel
1321 // VPN, or an app disallowed by the VPN), so the set of networks
1322 // returned includes the VPN's underlying networks and the system
1323 // default.
1324 enforceAccessPermission();
1325
Chalard Jean4133a122018-06-04 13:33:12 +09001326 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001327
1328 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001329 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001330 if (nc != null) {
1331 result.put(nai.network, nc);
1332 }
1333
Hugo Benichi69744342017-11-27 10:57:16 +09001334 synchronized (mVpns) {
1335 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001336 Vpn vpn = mVpns.get(userId);
1337 if (vpn != null) {
1338 Network[] networks = vpn.getUnderlyingNetworks();
1339 if (networks != null) {
1340 for (Network network : networks) {
1341 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001342 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001343 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001344 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001345 }
1346 }
1347 }
1348 }
1349 }
1350 }
1351
1352 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1353 out = result.values().toArray(out);
1354 return out;
1355 }
1356
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001357 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001358 public boolean isNetworkSupported(int networkType) {
1359 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001360 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001361 }
1362
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001363 /**
1364 * Return LinkProperties for the active (i.e., connected) default
1365 * network interface. It is assumed that at most one default network
1366 * is active at a time. If more than one is active, it is indeterminate
1367 * which will be returned.
1368 * @return the ip properties for the active network, or {@code null} if
1369 * none is active
1370 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001371 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001372 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001373 enforceAccessPermission();
1374 final int uid = Binder.getCallingUid();
1375 NetworkState state = getUnfilteredActiveNetworkState(uid);
1376 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001380 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001381 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001382 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1383 if (nai != null) {
1384 synchronized (nai) {
1385 return new LinkProperties(nai.linkProperties);
1386 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001387 }
1388 return null;
1389 }
1390
Robert Greenwalt12e67352014-05-13 21:41:06 -07001391 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001392 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001393 public LinkProperties getLinkProperties(Network network) {
1394 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001395 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1396 }
1397
1398 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1399 if (nai == null) {
1400 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001401 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001402 synchronized (nai) {
1403 return new LinkProperties(nai.linkProperties);
1404 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001405 }
1406
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001407 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001408 if (nai != null) {
1409 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001410 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001411 return networkCapabilitiesRestrictedForCallerPermissions(
1412 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001413 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001414 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001415 }
1416 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001417 return null;
1418 }
1419
1420 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001421 public NetworkCapabilities getNetworkCapabilities(Network network) {
1422 enforceAccessPermission();
1423 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1424 }
1425
Chalard Jeanb03a6222018-04-11 21:09:10 +09001426 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001427 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001428 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001429 if (!checkSettingsPermission(callerPid, callerUid)) {
1430 newNc.setUids(null);
1431 newNc.setSSID(null);
1432 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001433 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001434 }
1435
Chalard Jeanb552c462018-02-21 18:43:54 +09001436 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1437 if (!checkSettingsPermission()) {
1438 nc.setSingleUid(Binder.getCallingUid());
1439 }
1440 }
1441
Chalard Jean26aa91a2018-03-20 19:13:57 +09001442 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1443 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1444 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1445 }
1446 }
1447
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001448 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001449 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001450 // Require internal since we're handing out IMSI details
1451 enforceConnectivityInternalPermission();
1452
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001453 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001454 for (Network network : getAllNetworks()) {
1455 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1456 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001457 // TODO (b/73321673) : NetworkState contains a copy of the
1458 // NetworkCapabilities, which may contain UIDs of apps to which the
1459 // network applies. Should the UIDs be cleared so as not to leak or
1460 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001461 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001462 }
1463 }
1464 return result.toArray(new NetworkState[result.size()]);
1465 }
1466
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001467 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001468 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001469 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001470 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1471 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1472 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001473 }
1474
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001475 @Override
1476 public boolean isActiveNetworkMetered() {
1477 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001478
Eric Enslenc81ef192018-02-07 18:03:53 -08001479 final int uid = Binder.getCallingUid();
1480 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001481 if (caps != null) {
1482 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1483 } else {
1484 // Always return the most conservative value
1485 return true;
1486 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001487 }
1488
Jeff Sharkey216c1812012-08-05 14:29:23 -07001489 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1490 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001491 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001492 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001493 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001494 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001495 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001496
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001497 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 * Ensure that a network route exists to deliver traffic to the specified
1499 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001500 * @param networkType the type of the network over which traffic to the
1501 * specified host is to be routed
1502 * @param hostAddress the IP address of the host to which the route is
1503 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 * @return {@code true} on success, {@code false} on failure
1505 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001506 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001507 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001509 if (mProtectedNetworks.contains(networkType)) {
1510 enforceConnectivityInternalPermission();
1511 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001512
Chad Brubakerc0234532014-02-14 13:24:29 -08001513 InetAddress addr;
1514 try {
1515 addr = InetAddress.getByAddress(hostAddress);
1516 } catch (UnknownHostException e) {
1517 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1518 return false;
1519 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001522 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 return false;
1524 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001525
1526 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1527 if (nai == null) {
1528 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1529 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1530 } else {
1531 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1532 }
1533 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001534 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001535
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001536 DetailedState netState;
1537 synchronized (nai) {
1538 netState = nai.networkInfo.getDetailedState();
1539 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001540
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001541 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001542 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001543 log("requestRouteToHostAddress on down network "
1544 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001545 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001546 }
1547 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001549
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001550 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001551 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001552 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001553 LinkProperties lp;
1554 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001555 synchronized (nai) {
1556 lp = nai.linkProperties;
1557 netId = nai.network.netId;
1558 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001559 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001560 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1561 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001562 } finally {
1563 Binder.restoreCallingIdentity(token);
1564 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001565 }
1566
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001567 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001568 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001569 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001570 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001571 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001572 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001573 if (bestRoute.getGateway().equals(addr)) {
1574 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001575 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001576 } else {
1577 // if we will connect to this through another route, add a direct route
1578 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001579 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001580 }
1581 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001582 if (DBG) log("Adding legacy route " + bestRoute +
1583 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001584 try {
1585 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1586 } catch (Exception e) {
1587 // never crash - catch them all
1588 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001589 return false;
1590 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001591 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
1593
dalyk7301aa42018-03-05 12:42:22 -05001594 @VisibleForTesting
1595 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1596 @Override
1597 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1598 String hostname, boolean validated) {
1599 try {
1600 mHandler.sendMessage(mHandler.obtainMessage(
1601 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1602 new PrivateDnsValidationUpdate(netId,
1603 InetAddress.parseNumericAddress(ipAddress),
1604 hostname, validated)));
1605 } catch (IllegalArgumentException e) {
1606 loge("Error parsing ip address in validation event");
1607 }
1608 }
1609 };
1610
1611 @VisibleForTesting
1612 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001613 final IIpConnectivityMetrics ipConnectivityMetrics =
1614 IIpConnectivityMetrics.Stub.asInterface(
1615 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1616 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001617 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001618 return;
dalyk7301aa42018-03-05 12:42:22 -05001619 }
1620
1621 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001622 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001623 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1624 mNetdEventCallback);
1625 } catch (Exception e) {
1626 loge("Error registering netd callback: " + e);
1627 }
1628 }
1629
Jeff Sharkey75d31892018-01-18 22:01:59 +09001630 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001631 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001632 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001633 // TODO: notify UID when it has requested targeted updates
1634 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001635 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001636 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001637 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001638 if (restrictBackground) {
1639 log("onRestrictBackgroundChanged(true): disabling tethering");
1640 mTethering.untetherAll();
1641 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001642 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001643 };
1644
Robin Lee3b3dd942015-05-12 18:14:58 +01001645 /**
1646 * Require that the caller is either in the same user or has appropriate permission to interact
1647 * across users.
1648 *
1649 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1650 */
1651 private void enforceCrossUserPermission(int userId) {
1652 if (userId == UserHandle.getCallingUserId()) {
1653 // Not a cross-user call.
1654 return;
1655 }
1656 mContext.enforceCallingOrSelfPermission(
1657 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1658 "ConnectivityService");
1659 }
1660
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001661 private void enforceInternetPermission() {
1662 mContext.enforceCallingOrSelfPermission(
1663 android.Manifest.permission.INTERNET,
1664 "ConnectivityService");
1665 }
1666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001668 mContext.enforceCallingOrSelfPermission(
1669 android.Manifest.permission.ACCESS_NETWORK_STATE,
1670 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672
1673 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001674 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676
Charles He36738632017-05-15 17:07:18 +01001677 private void enforceSettingsPermission() {
1678 mContext.enforceCallingOrSelfPermission(
1679 android.Manifest.permission.NETWORK_SETTINGS,
1680 "ConnectivityService");
1681 }
1682
Chalard Jeanb552c462018-02-21 18:43:54 +09001683 private boolean checkSettingsPermission() {
1684 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1685 android.Manifest.permission.NETWORK_SETTINGS);
1686 }
1687
1688 private boolean checkSettingsPermission(int pid, int uid) {
1689 return PERMISSION_GRANTED == mContext.checkPermission(
1690 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1691 }
1692
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001693 private void enforceTetherAccessPermission() {
1694 mContext.enforceCallingOrSelfPermission(
1695 android.Manifest.permission.ACCESS_NETWORK_STATE,
1696 "ConnectivityService");
1697 }
1698
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001699 private void enforceConnectivityInternalPermission() {
1700 mContext.enforceCallingOrSelfPermission(
1701 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1702 "ConnectivityService");
1703 }
1704
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001705 private boolean checkNetworkStackPermission() {
1706 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1707 android.Manifest.permission.NETWORK_STACK);
1708 }
1709
Hugo Benichi514da602016-07-19 15:59:27 +09001710 private void enforceConnectivityRestrictedNetworksPermission() {
1711 try {
1712 mContext.enforceCallingOrSelfPermission(
1713 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1714 "ConnectivityService");
1715 return;
1716 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1717 enforceConnectivityInternalPermission();
1718 }
1719
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001720 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001721 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001722 }
1723
Lorenzo Colitti18660282016-07-04 12:55:44 +09001724 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001725 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001726 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001727 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001728 }
1729
1730 private void sendInetConditionBroadcast(NetworkInfo info) {
1731 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1732 }
1733
Wink Saville628b0852011-08-04 15:01:58 -07001734 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001735 synchronized (mVpns) {
1736 if (mLockdownTracker != null) {
1737 info = new NetworkInfo(info);
1738 mLockdownTracker.augmentNetworkInfo(info);
1739 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001740 }
1741
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001742 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001743 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001744 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 if (info.isFailover()) {
1746 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1747 info.setFailover(false);
1748 }
1749 if (info.getReason() != null) {
1750 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1751 }
1752 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001753 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1754 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001756 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001757 return intent;
1758 }
1759
1760 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1761 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1762 }
1763
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001764 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001765 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1766 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1767 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001768 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001769 final long ident = Binder.clearCallingIdentity();
1770 try {
1771 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1772 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1773 } finally {
1774 Binder.restoreCallingIdentity(ident);
1775 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001776 }
1777
Mike Lockwood0f79b542009-08-14 14:18:49 -04001778 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001779 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001780 if (!mSystemReady) {
1781 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001782 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001784 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001785 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001786 }
1787
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001788 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001789 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001790 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001791 final NetworkInfo ni = intent.getParcelableExtra(
1792 ConnectivityManager.EXTRA_NETWORK_INFO);
1793 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1794 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1795 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001796 } else {
1797 BroadcastOptions opts = BroadcastOptions.makeBasic();
1798 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1799 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001800 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001801 final IBatteryStats bs = BatteryStatsService.getService();
1802 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001803 bs.noteConnectivityChanged(intent.getIntExtra(
1804 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001805 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001806 } catch (RemoteException e) {
1807 }
Chad Brubakerac925012018-03-08 10:37:09 -08001808 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001809 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001810 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001811 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001812 } finally {
1813 Binder.restoreCallingIdentity(ident);
1814 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001815 }
1816 }
1817
1818 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001819 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001820 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001821
Hugo Benichi20035e02017-04-26 14:53:28 +09001822 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001823 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001824 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001825 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001826 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001827 }
1828 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001829 // load the global proxy at startup
1830 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001831
Robin Lee244ce8e2016-01-05 18:03:46 +00001832 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1833 // for user to unlock device too.
1834 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001835
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001836 // Create network requests for always-on networks.
1837 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09001838
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001839 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001840
1841 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001845 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001846 *
1847 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001848 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001849 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001850 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1851 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001852
1853 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001855
Robert Greenwalt7b816022014-04-18 15:25:25 -07001856 if (networkAgent.networkCapabilities.hasTransport(
1857 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001858 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1859 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001860 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001861 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001862 } else if (networkAgent.networkCapabilities.hasTransport(
1863 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001864 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1865 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001866 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001867 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001868 } else {
1869 // do not track any other networks
1870 timeout = 0;
1871 }
1872
Robert Greenwalt7b816022014-04-18 15:25:25 -07001873 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001874 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001875 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001876 } catch (Exception e) {
1877 // You shall not crash!
1878 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001879 }
1880 }
1881 }
1882
1883 /**
1884 * Remove data activity tracking when network disconnects.
1885 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001886 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1887 final String iface = networkAgent.linkProperties.getInterfaceName();
1888 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001889
Robert Greenwalt7b816022014-04-18 15:25:25 -07001890 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1891 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001892 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001893 // the call fails silently if no idle timer setup for this interface
Haoyu Bai04124232012-06-28 15:26:19 -07001894 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001895 } catch (Exception e) {
1896 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001897 }
1898 }
1899 }
1900
1901 /**
Chalard Jean4d660112018-06-04 16:52:49 +09001902 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09001903 * and set it on it's iface.
1904 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001905 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1906 final String iface = newLp.getInterfaceName();
1907 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001908 if (oldLp == null && mtu == 0) {
1909 // Silently ignore unset MTU value.
1910 return;
1911 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001912 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1913 if (VDBG) log("identical MTU - not setting");
1914 return;
1915 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001916 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001917 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001918 return;
1919 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001920
w1997615afd812014-08-05 15:18:11 -07001921 // Cannot set MTU without interface name
1922 if (TextUtils.isEmpty(iface)) {
1923 loge("Setting MTU size with null iface.");
1924 return;
1925 }
1926
Robert Greenwalt7b816022014-04-18 15:25:25 -07001927 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001928 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001929 mNetd.setMtu(iface, mtu);
1930 } catch (Exception e) {
1931 Slog.e(TAG, "exception in setMtu()" + e);
1932 }
1933 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001934
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001935 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001936 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1937
1938 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001939 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001940 protected MockableSystemProperties getSystemProperties() {
1941 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001942 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001943
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001944 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1945 if (isDefaultNetwork(nai) == false) {
1946 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001947 }
1948
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001949 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1950 String[] values = null;
1951 if (tcpBufferSizes != null) {
1952 values = tcpBufferSizes.split(",");
1953 }
1954
1955 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001956 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001957 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1958 values = tcpBufferSizes.split(",");
1959 }
1960
1961 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1962
1963 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001964 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001965
1966 final String prefix = "/sys/kernel/ipv4/tcp_";
1967 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1968 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1969 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1970 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1971 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1972 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1973 mCurrentTcpBufferSizes = tcpBufferSizes;
1974 } catch (IOException e) {
1975 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001976 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001977
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001978 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001979 Settings.Global.TCP_DEFAULT_INIT_RWND,
1980 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001981 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1982 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001983 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001984 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001985 }
1986
Robert Greenwalt562cc542014-05-15 18:07:26 -07001987 @Override
1988 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001989 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001990 NETWORK_RESTORE_DELAY_PROP_NAME);
1991 if(restoreDefaultNetworkDelayStr != null &&
1992 restoreDefaultNetworkDelayStr.length() != 0) {
1993 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001994 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001995 } catch (NumberFormatException e) {
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001998 // if the system property isn't set, use the value for the apn type
1999 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2000
2001 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2002 (mNetConfigs[networkType] != null)) {
2003 ret = mNetConfigs[networkType].restoreTime;
2004 }
2005 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 }
2007
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002008 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2009 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2010 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002011 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002012 // Start gathering diagnostic information.
2013 netDiags.add(new NetworkDiagnostics(
2014 nai.network,
2015 new LinkProperties(nai.linkProperties), // Must be a copy.
2016 DIAG_TIME_MS));
2017 }
2018
2019 for (NetworkDiagnostics netDiag : netDiags) {
2020 pw.println();
2021 netDiag.waitForMeasurements();
2022 netDiag.dump(pw);
2023 }
2024 }
2025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002027 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002028 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2029 }
2030
2031 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002032 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002033 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002034 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002035
Erik Kline3f8306b2018-05-01 16:51:44 +09002036 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002037 dumpNetworkDiagnostics(pw);
2038 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002039 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002040 mTethering.dump(fd, pw, args);
2041 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002042 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2043 dumpNetworks(pw);
2044 return;
2045 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2046 dumpNetworkRequests(pw);
2047 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002048 }
Erik Kline379747a2015-06-05 17:47:34 +09002049
Lorenzo Colittie3805462015-06-03 11:18:24 +09002050 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002051 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002052 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002053 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002054 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002055 pw.println();
2056
Paul Jensen85cf78e2015-06-25 13:25:07 -04002057 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002058 pw.print("Active default network: ");
2059 if (defaultNai == null) {
2060 pw.println("none");
2061 } else {
2062 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002064 pw.println();
2065
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002066 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002067 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002068 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002069 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002070 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002071
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002072 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002073 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002074 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002075 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002076 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002077
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002078 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002079
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002080 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002081 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002082
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002083 pw.println();
2084 mKeepaliveTracker.dump(pw);
2085
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002086 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002087 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002088
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002089 pw.println();
2090 mMultipathPolicyTracker.dump(pw);
2091
Erik Kline3f8306b2018-05-01 16:51:44 +09002092 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002093 pw.println();
2094 synchronized (mValidationLogs) {
2095 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002096 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002097 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002098 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002099 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002100 pw.decreaseIndent();
2101 }
2102 }
Erik Kline7523eb32015-07-09 18:24:03 +09002103
2104 pw.println();
2105 pw.println("mNetworkRequestInfoLogs (most recent first):");
2106 pw.increaseIndent();
2107 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2108 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002109
2110 pw.println();
2111 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2112 pw.increaseIndent();
2113 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2114 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002115
2116 pw.println();
2117 pw.println("NetTransition WakeLock activity (most recent first):");
2118 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002119 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2120 pw.println("total releases: " + mTotalWakelockReleases);
2121 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2122 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2123 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2124 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2125 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2126 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002127 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002128
2129 pw.println();
2130 pw.println("bandwidth update requests (by uid):");
2131 pw.increaseIndent();
2132 synchronized (mBandwidthRequests) {
2133 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2134 pw.println("[" + mBandwidthRequests.keyAt(i)
2135 + "]: " + mBandwidthRequests.valueAt(i));
2136 }
2137 }
2138 pw.decreaseIndent();
2139
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002140 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143
Hugo Benichi14683812018-09-03 08:32:56 +09002144 private void dumpNetworks(IndentingPrintWriter pw) {
2145 for (NetworkAgentInfo nai : networksSortedById()) {
2146 pw.println(nai.toString());
2147 pw.increaseIndent();
2148 pw.println(String.format(
2149 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2150 nai.numForegroundNetworkRequests(),
2151 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2152 nai.numBackgroundNetworkRequests(),
2153 nai.numNetworkRequests()));
2154 pw.increaseIndent();
2155 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2156 pw.println(nai.requestAt(i).toString());
2157 }
2158 pw.decreaseIndent();
2159 pw.println("Lingered:");
2160 pw.increaseIndent();
2161 nai.dumpLingerTimers(pw);
2162 pw.decreaseIndent();
2163 pw.decreaseIndent();
2164 }
2165 }
2166
2167 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2168 for (NetworkRequestInfo nri : requestsSortedById()) {
2169 pw.println(nri.toString());
2170 }
2171 }
2172
Hugo Benichia2a917c2018-09-03 08:19:02 +09002173 /**
2174 * Return an array of all current NetworkAgentInfos sorted by network id.
2175 */
2176 private NetworkAgentInfo[] networksSortedById() {
2177 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2178 networks = mNetworkAgentInfos.values().toArray(networks);
2179 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2180 return networks;
2181 }
2182
2183 /**
2184 * Return an array of all current NetworkRequest sorted by request id.
2185 */
2186 private NetworkRequestInfo[] requestsSortedById() {
2187 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2188 requests = mNetworkRequests.values().toArray(requests);
2189 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2190 return requests;
2191 }
2192
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002193 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002194 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002195 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002196 if (officialNai != null && officialNai.equals(nai)) return true;
2197 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002198 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002199 " - " + nai);
2200 }
2201 return false;
2202 }
2203
Robert Greenwalt42acef32009-08-12 16:08:25 -07002204 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002205 private class NetworkStateTrackerHandler extends Handler {
2206 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002207 super(looper);
2208 }
2209
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002210 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002212 default:
2213 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002214 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 handleAsyncChannelHalfConnect(msg);
2216 break;
2217 }
2218 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2219 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2220 if (nai != null) nai.asyncChannel.disconnect();
2221 break;
2222 }
2223 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2224 handleAsyncChannelDisconnected(msg);
2225 break;
2226 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002227 }
2228 return true;
2229 }
2230
2231 private void maybeHandleNetworkAgentMessage(Message msg) {
2232 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2233 if (nai == null) {
2234 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002235 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002236 }
2237 return;
2238 }
2239
2240 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002241 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002242 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2243 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002244 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2245 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002246 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002247 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002248 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002249 break;
2250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002251 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002252 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002253 break;
2254 }
2255 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002256 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002257 updateNetworkInfo(nai, info);
2258 break;
2259 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002260 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002261 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002262 break;
2263 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002264 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002265 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2266 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002267 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002268 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002269 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002270 break;
2271 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002272 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002273 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2274 break;
2275 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002276 }
2277 }
2278
2279 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2280 switch (msg.what) {
2281 default:
2282 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002283 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002284 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002285 if (nai == null) break;
2286
2287 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2288 final boolean wasValidated = nai.lastValidated;
2289 final boolean wasDefault = isDefaultNetwork(nai);
2290
Erik Klinea24d4592018-01-11 21:07:29 +09002291 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2292
Erik Klinea24d4592018-01-11 21:07:29 +09002293 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002294 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2295 ? " with redirect to " + redirectUrl
2296 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002297 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2298 }
Erik Klinea24d4592018-01-11 21:07:29 +09002299 if (valid != nai.lastValidated) {
2300 if (wasDefault) {
2301 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2302 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002303 }
Erik Klinea24d4592018-01-11 21:07:29 +09002304 final int oldScore = nai.getCurrentScore();
2305 nai.lastValidated = valid;
2306 nai.everValidated |= valid;
2307 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2308 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2309 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002310 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002311 }
2312 updateInetCondition(nai);
2313 // Let the NetworkAgent know the state of its network
2314 Bundle redirectUrlBundle = new Bundle();
2315 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2316 nai.asyncChannel.sendMessage(
2317 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2318 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2319 0, redirectUrlBundle);
2320 if (wasValidated && !nai.lastValidated) {
2321 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002322 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002323 break;
2324 }
Paul Jensen869868be2014-05-15 10:33:05 -04002325 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002326 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002327 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002328 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002329 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002330 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002331 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002332 nai.lastCaptivePortalDetected = visible;
2333 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002334 if (nai.lastCaptivePortalDetected &&
2335 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2336 if (DBG) log("Avoiding captive portal network: " + nai.name());
2337 nai.asyncChannel.sendMessage(
2338 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2339 teardownUnneededNetwork(nai);
2340 break;
2341 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002342 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002343 }
2344 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002345 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002346 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002347 if (nai == null) {
2348 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2349 break;
2350 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002351 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002352 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002353 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002354 }
Paul Jensen869868be2014-05-15 10:33:05 -04002355 }
Paul Jensen869868be2014-05-15 10:33:05 -04002356 break;
2357 }
Erik Klinea24d4592018-01-11 21:07:29 +09002358 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002359 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002360 if (nai == null) break;
2361
Erik Kline736353a2018-03-21 07:18:33 -07002362 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002363 break;
2364 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002365 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002366 return true;
2367 }
2368
Calvin Onbe96da12016-10-11 15:10:46 -07002369 private int getCaptivePortalMode() {
2370 return Settings.Global.getInt(mContext.getContentResolver(),
2371 Settings.Global.CAPTIVE_PORTAL_MODE,
2372 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2373 }
2374
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002375 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2376 switch (msg.what) {
2377 default:
2378 return false;
2379 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2380 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2381 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2382 handleLingerComplete(nai);
2383 }
2384 break;
2385 }
2386 }
2387 return true;
2388 }
2389
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002390 @Override
2391 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002392 if (!maybeHandleAsyncChannelMessage(msg) &&
2393 !maybeHandleNetworkMonitorMessage(msg) &&
2394 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002395 maybeHandleNetworkAgentMessage(msg);
2396 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002397 }
2398 }
2399
Erik Kline736353a2018-03-21 07:18:33 -07002400 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2401 return NetworkMonitor.isValidationRequired(
2402 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2403 }
2404
Erik Klinec6d00222018-06-26 18:53:43 +09002405 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2406 if (nai == null) return;
2407 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2408 // in order to restart a validation pass from within netd.
2409 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2410 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2411 updateDnses(nai.linkProperties, null, nai.network.netId);
2412 }
2413 }
2414
Erik Klinea24d4592018-01-11 21:07:29 +09002415 private void handlePrivateDnsSettingsChanged() {
2416 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2417
2418 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002419 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002420 if (networkRequiresValidation(nai)) {
2421 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2422 }
Erik Klinea24d4592018-01-11 21:07:29 +09002423 }
2424 }
2425
Erik Kline736353a2018-03-21 07:18:33 -07002426 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2427 // Private DNS only ever applies to networks that might provide
2428 // Internet access and therefore also require validation.
2429 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002430
Erik Kline736353a2018-03-21 07:18:33 -07002431 // Notify the NetworkMonitor thread in case it needs to cancel or
2432 // schedule DNS resolutions. If a DNS resolution is required the
2433 // result will be sent back to us.
2434 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2435
2436 // With Private DNS bypass support, we can proceed to update the
2437 // Private DNS config immediately, even if we're in strict mode
2438 // and have not yet resolved the provider name into a set of IPs.
2439 updatePrivateDns(nai, cfg);
2440 }
2441
2442 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2443 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002444 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002445 }
2446
dalyk7301aa42018-03-05 12:42:22 -05002447 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2448 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2449 if (nai == null) {
2450 return;
2451 }
2452 mDnsManager.updatePrivateDnsValidation(update);
2453 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2454 }
2455
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002456 private void updateLingerState(NetworkAgentInfo nai, long now) {
2457 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2458 // 2. If the network was lingering and there are now requests, unlinger it.
2459 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2460 // one lingered request, start lingering.
2461 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002462 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002463 if (DBG) log("Unlingering " + nai.name());
2464 nai.unlinger();
2465 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002466 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002467 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002468 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002469 nai.linger();
2470 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2471 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2472 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002473 }
2474
Robert Greenwalt7b816022014-04-18 15:25:25 -07002475 private void handleAsyncChannelHalfConnect(Message msg) {
2476 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002477 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002478 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2479 if (VDBG) log("NetworkFactory connected");
2480 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002481 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002482 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002483 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002484 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002485 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002486 }
2487 } else {
2488 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002489 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002490 }
2491 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2492 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2493 if (VDBG) log("NetworkAgent connected");
2494 // A network agent has requested a connection. Establish the connection.
2495 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2496 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2497 } else {
2498 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002499 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002500 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002501 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002502 synchronized (mNetworkForNetId) {
2503 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002504 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002505 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002506 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002507 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002508 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002509 }
2510 }
2511 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002512
Chalard Jean392971c2018-05-11 20:19:20 +09002513 // This is a no-op if it's called with a message designating a network that has
2514 // already been destroyed, because its reference will not be found in the relevant
2515 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002516 private void handleAsyncChannelDisconnected(Message msg) {
2517 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2518 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002519 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002520 } else {
2521 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2522 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002523 }
2524 }
2525
Chalard Jean392971c2018-05-11 20:19:20 +09002526 // Destroys a network, remove references to it from the internal state managed by
2527 // ConnectivityService, free its interfaces and clean up.
2528 // Must be called on the Handler thread.
2529 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2530 if (DBG) {
2531 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2532 }
2533 // A network agent has disconnected.
2534 // TODO - if we move the logic to the network agent (have them disconnect
2535 // because they lost all their requests or because their score isn't good)
2536 // then they would disconnect organically, report their new state and then
2537 // disconnect the channel.
2538 if (nai.networkInfo.isConnected()) {
2539 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2540 null, null);
2541 }
2542 final boolean wasDefault = isDefaultNetwork(nai);
2543 if (wasDefault) {
2544 mDefaultInetConditionPublished = 0;
2545 // Log default network disconnection before required book-keeping.
2546 // Let rematchAllNetworksAndRequests() below record a new default network event
2547 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2548 // whose timestamps tell how long it takes to recover a default network.
2549 long now = SystemClock.elapsedRealtime();
2550 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2551 }
2552 notifyIfacesChangedForNetworkStats();
2553 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2554 // by other networks that are already connected. Perhaps that can be done by
2555 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2556 // of rematchAllNetworksAndRequests
2557 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2558 mKeepaliveTracker.handleStopAllKeepalives(nai,
2559 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2560 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2561 // Disable wakeup packet monitoring for each interface.
2562 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2563 }
2564 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2565 mNetworkAgentInfos.remove(nai.messenger);
2566 nai.maybeStopClat();
2567 synchronized (mNetworkForNetId) {
2568 // Remove the NetworkAgent, but don't mark the netId as
2569 // available until we've told netd to delete it below.
2570 mNetworkForNetId.remove(nai.network.netId);
2571 }
2572 // Remove all previously satisfied requests.
2573 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2574 NetworkRequest request = nai.requestAt(i);
2575 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2576 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2577 clearNetworkForRequest(request.requestId);
2578 sendUpdatedScoreToFactories(request, 0);
2579 }
2580 }
2581 nai.clearLingerState();
2582 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
2583 removeDataActivityTracking(nai);
2584 notifyLockdownVpn(nai);
2585 ensureNetworkTransitionWakelock(nai.name());
2586 }
2587 mLegacyTypeTracker.remove(nai, wasDefault);
2588 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2589 updateAllVpnsCapabilities();
2590 }
2591 rematchAllNetworksAndRequests(null, 0);
2592 mLingerMonitor.noteDisconnect(nai);
2593 if (nai.created) {
2594 // Tell netd to clean up the configuration for this network
2595 // (routing rules, DNS, etc).
2596 // This may be slow as it requires a lot of netd shelling out to ip and
2597 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2598 // after we've rematched networks with requests which should make a potential
2599 // fallback network the default or requested a new network from the
2600 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2601 // long time.
2602 try {
2603 mNetd.removeNetwork(nai.network.netId);
2604 } catch (Exception e) {
2605 loge("Exception removing network: " + e);
2606 }
2607 mDnsManager.removeNetwork(nai.network);
2608 }
2609 synchronized (mNetworkForNetId) {
2610 mNetIdInUse.delete(nai.network.netId);
2611 }
2612 }
2613
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002614 // If this method proves to be too slow then we can maintain a separate
2615 // pendingIntent => NetworkRequestInfo map.
2616 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2617 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2618 Intent intent = pendingIntent.getIntent();
2619 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2620 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2621 if (existingPendingIntent != null &&
2622 existingPendingIntent.getIntent().filterEquals(intent)) {
2623 return entry.getValue();
2624 }
2625 }
2626 return null;
2627 }
2628
2629 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2630 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2631
2632 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2633 if (existingRequest != null) { // remove the existing request.
2634 if (DBG) log("Replacing " + existingRequest.request + " with "
2635 + nri.request + " because their intents matched.");
2636 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2637 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002638 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002639 }
2640
Erik Klineda4bfa82015-04-30 12:58:40 +09002641 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002642 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002643 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002644 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002645 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002646 if (nri.request.networkCapabilities.hasSignalStrength() &&
2647 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2648 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002649 }
2650 }
2651 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002652 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002653 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002654 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002655 }
2656 }
2657
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002658 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2659 int callingUid) {
2660 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2661 if (nri != null) {
2662 handleReleaseNetworkRequest(nri.request, callingUid);
2663 }
2664 }
2665
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002666 // Determines whether the network is the best (or could become the best, if it validated), for
2667 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2668 // on the value of reason:
2669 //
2670 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2671 // then it should be torn down.
2672 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2673 // then it should be lingered.
2674 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2675 final int numRequests;
2676 switch (reason) {
2677 case TEARDOWN:
2678 numRequests = nai.numRequestNetworkRequests();
2679 break;
2680 case LINGER:
2681 numRequests = nai.numForegroundNetworkRequests();
2682 break;
2683 default:
2684 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2685 return true;
2686 }
2687
2688 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002689 return false;
2690 }
Paul Jensene0988542015-06-25 15:30:08 -04002691 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002692 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2693 // Background requests don't affect lingering.
2694 continue;
2695 }
2696
Paul Jensene0988542015-06-25 15:30:08 -04002697 // If this Network is already the highest scoring Network for a request, or if
2698 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002699 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002700 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002701 // Note that this catches two important cases:
2702 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2703 // is currently satisfying the request. This is desirable when
2704 // cellular ends up validating but WiFi does not.
2705 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002706 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002707 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002708 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002709 nai.getCurrentScoreAsValidated())) {
2710 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002711 }
2712 }
Paul Jensene0988542015-06-25 15:30:08 -04002713 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002714 }
2715
Erik Klineacdd6392016-07-07 16:50:58 +09002716 private NetworkRequestInfo getNriForAppRequest(
2717 NetworkRequest request, int callingUid, String requestedOperation) {
2718 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2719
Robert Greenwalt9258c642014-03-26 16:47:06 -07002720 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002721 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002722 log(String.format("UID %d attempted to %s for unowned request %s",
2723 callingUid, requestedOperation, nri));
2724 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002725 }
Erik Klineacdd6392016-07-07 16:50:58 +09002726 }
2727
2728 return nri;
2729 }
2730
Erik Kline57faba92015-11-25 12:49:38 +09002731 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002732 if (mNetworkRequests.get(nri.request) == null) {
2733 return;
Erik Kline57faba92015-11-25 12:49:38 +09002734 }
Hugo Benichicd952782017-09-20 11:20:14 +09002735 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002736 return;
2737 }
2738 if (VDBG || (DBG && nri.request.isRequest())) {
2739 log("releasing " + nri.request + " (timeout)");
2740 }
2741 handleRemoveNetworkRequest(nri);
2742 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002743 }
2744
Erik Klineacdd6392016-07-07 16:50:58 +09002745 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002746 final NetworkRequestInfo nri =
2747 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2748 if (nri == null) {
2749 return;
Erik Kline57faba92015-11-25 12:49:38 +09002750 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002751 if (VDBG || (DBG && nri.request.isRequest())) {
2752 log("releasing " + nri.request + " (release request)");
2753 }
2754 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002755 }
Erik Klineacdd6392016-07-07 16:50:58 +09002756
Hugo Benichidba33db2017-03-23 22:40:44 +09002757 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002758 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002759 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002760
Erik Klineacdd6392016-07-07 16:50:58 +09002761 synchronized (mUidToNetworkRequestCount) {
2762 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2763 if (requests < 1) {
2764 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2765 nri.mUid);
2766 } else if (requests == 1) {
2767 mUidToNetworkRequestCount.removeAt(
2768 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2769 } else {
2770 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2771 }
2772 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002773
Erik Klineacdd6392016-07-07 16:50:58 +09002774 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2775 if (nri.request.isRequest()) {
2776 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002777 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002778 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002779 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002780 nai.removeRequest(nri.request.requestId);
2781 if (VDBG) {
2782 log(" Removing from current network " + nai.name() +
2783 ", leaving " + nai.numNetworkRequests() + " requests.");
2784 }
2785 // If there are still lingered requests on this network, don't tear it down,
2786 // but resume lingering instead.
2787 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002788 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002789 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2790 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002791 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002792 wasKept = true;
2793 }
Hugo Benichicd952782017-09-20 11:20:14 +09002794 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002795 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2796 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002797 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002798 }
Erik Klineacdd6392016-07-07 16:50:58 +09002799 }
2800
2801 // TODO: remove this code once we know that the Slog.wtf is never hit.
2802 //
2803 // Find all networks that are satisfying this request and remove the request
2804 // from their request lists.
2805 // TODO - it's my understanding that for a request there is only a single
2806 // network satisfying it, so this loop is wasteful
2807 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2808 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2809 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2810 otherNai.name() + ", but mNetworkAgentInfos says " +
2811 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002812 }
2813 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002814
Erik Klineacdd6392016-07-07 16:50:58 +09002815 // Maintain the illusion. When this request arrived, we might have pretended
2816 // that a network connected to serve it, even though the network was already
2817 // connected. Now that this request has gone away, we might have to pretend
2818 // that the network disconnected. LegacyTypeTracker will generate that
2819 // phantom disconnect for this type.
2820 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2821 boolean doRemove = true;
2822 if (wasKept) {
2823 // check if any of the remaining requests for this network are for the
2824 // same legacy type - if so, don't remove the nai
2825 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2826 NetworkRequest otherRequest = nai.requestAt(i);
2827 if (otherRequest.legacyType == nri.request.legacyType &&
2828 otherRequest.isRequest()) {
2829 if (DBG) log(" still have other legacy request - leaving");
2830 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002831 }
2832 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002833 }
2834
Erik Klineacdd6392016-07-07 16:50:58 +09002835 if (doRemove) {
2836 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002837 }
2838 }
Erik Klineacdd6392016-07-07 16:50:58 +09002839
2840 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2841 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2842 nri.request);
2843 }
2844 } else {
2845 // listens don't have a singular affectedNetwork. Check all networks to see
2846 // if this listen request applies and remove it.
2847 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2848 nai.removeRequest(nri.request.requestId);
2849 if (nri.request.networkCapabilities.hasSignalStrength() &&
2850 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2851 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2852 }
2853 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002854 }
2855 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002856
Lorenzo Colitti18660282016-07-04 12:55:44 +09002857 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002858 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2859 enforceConnectivityInternalPermission();
2860 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002861 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002862 }
2863
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002864 @Override
2865 public void setAvoidUnvalidated(Network network) {
2866 enforceConnectivityInternalPermission();
2867 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2868 }
2869
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002870 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2871 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2872 " accept=" + accept + " always=" + always);
2873
2874 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2875 if (nai == null) {
2876 // Nothing to do.
2877 return;
2878 }
2879
2880 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002881 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002882 return;
2883 }
2884
2885 if (!nai.networkMisc.explicitlySelected) {
2886 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2887 }
2888
2889 if (accept != nai.networkMisc.acceptUnvalidated) {
2890 int oldScore = nai.getCurrentScore();
2891 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002892 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002893 sendUpdatedScoreToFactories(nai);
2894 }
2895
2896 if (always) {
2897 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002898 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002899 }
2900
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002901 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002902 // Tell the NetworkAgent to not automatically reconnect to the network.
2903 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09002904 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04002905 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002906 }
2907
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002908 }
2909
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002910 private void handleSetAvoidUnvalidated(Network network) {
2911 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2912 if (nai == null || nai.lastValidated) {
2913 // Nothing to do. The network either disconnected or revalidated.
2914 return;
2915 }
2916 if (!nai.avoidUnvalidated) {
2917 int oldScore = nai.getCurrentScore();
2918 nai.avoidUnvalidated = true;
2919 rematchAllNetworksAndRequests(nai, oldScore);
2920 sendUpdatedScoreToFactories(nai);
2921 }
2922 }
2923
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002924 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002925 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002926 mHandler.sendMessageDelayed(
2927 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2928 PROMPT_UNVALIDATED_DELAY_MS);
2929 }
2930
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002931 @Override
2932 public void startCaptivePortalApp(Network network) {
2933 enforceConnectivityInternalPermission();
2934 mHandler.post(() -> {
2935 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2936 if (nai == null) return;
2937 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2938 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2939 });
2940 }
2941
Hugo Benichic8e9e122016-09-14 23:23:08 +00002942 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002943 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002944 }
2945
Erik Kline065ab6e2016-10-02 18:02:14 +09002946 private void rematchForAvoidBadWifiUpdate() {
2947 rematchAllNetworksAndRequests(null, 0);
2948 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2949 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2950 sendUpdatedScoreToFactories(nai);
2951 }
2952 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002953 }
2954
Erik Kline065ab6e2016-10-02 18:02:14 +09002955 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002956 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002957 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002958 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002959 if (!configRestrict) {
2960 pw.println("Bad Wi-Fi avoidance: unrestricted");
2961 return;
2962 }
2963
2964 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2965 pw.increaseIndent();
2966 pw.println("Config restrict: " + configRestrict);
2967
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002968 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002969 String description;
2970 // Can't use a switch statement because strings are legal case labels, but null is not.
2971 if ("0".equals(value)) {
2972 description = "get stuck";
2973 } else if (value == null) {
2974 description = "prompt";
2975 } else if ("1".equals(value)) {
2976 description = "avoid";
2977 } else {
2978 description = value + " (?)";
2979 }
2980 pw.println("User setting: " + description);
2981 pw.println("Network overrides:");
2982 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09002983 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002984 if (nai.avoidUnvalidated) {
2985 pw.println(nai.name());
2986 }
2987 }
2988 pw.decreaseIndent();
2989 pw.decreaseIndent();
2990 }
2991
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002992 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2993 final String action;
2994 switch (type) {
2995 case NO_INTERNET:
2996 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2997 break;
2998 case LOST_INTERNET:
2999 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3000 break;
3001 default:
3002 Slog.wtf(TAG, "Unknown notification type " + type);
3003 return;
3004 }
3005
3006 Intent intent = new Intent(action);
3007 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3008 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3009 intent.setClassName("com.android.settings",
3010 "com.android.settings.wifi.WifiNoInternetDialog");
3011
3012 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3013 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3014 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3015 }
3016
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003017 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003018 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003019 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3020
3021 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3022 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003023 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003024 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003025 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3026 return;
3027 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003028 showValidationNotification(nai, NotificationType.NO_INTERNET);
3029 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003030
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003031 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3032 NetworkCapabilities nc = nai.networkCapabilities;
3033 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003034
Erik Kline065ab6e2016-10-02 18:02:14 +09003035 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003036 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003037 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3038 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003039 }
3040
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003041 @Override
3042 public int getMultipathPreference(Network network) {
3043 enforceAccessPermission();
3044
3045 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003046 if (nai != null && nai.networkCapabilities
3047 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003048 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3049 }
3050
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003051 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3052 if (networkPreference != null) {
3053 return networkPreference;
3054 }
3055
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003056 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3057 }
3058
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003059 private class InternalHandler extends Handler {
3060 public InternalHandler(Looper looper) {
3061 super(looper);
3062 }
3063
3064 @Override
3065 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003066 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003067 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003068 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003069 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003070 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003071 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003072 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003073 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003074 break;
3075 }
Jason Monkdecd2952013-10-10 14:02:51 -04003076 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003077 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003078 break;
3079 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003080 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003081 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3082 break;
3083 }
3084 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3085 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003086 break;
3087 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003088 case EVENT_REGISTER_NETWORK_AGENT: {
3089 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3090 break;
3091 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003092 case EVENT_REGISTER_NETWORK_REQUEST:
3093 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003094 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003095 break;
3096 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003097 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3098 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003099 handleRegisterNetworkRequestWithIntent(msg);
3100 break;
3101 }
Erik Kline57faba92015-11-25 12:49:38 +09003102 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3103 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3104 handleTimedOutNetworkRequest(nri);
3105 break;
3106 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003107 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3108 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3109 break;
3110 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003111 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003112 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003113 break;
3114 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003115 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003116 Network network = (Network) msg.obj;
3117 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003118 break;
3119 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003120 case EVENT_SET_AVOID_UNVALIDATED: {
3121 handleSetAvoidUnvalidated((Network) msg.obj);
3122 break;
3123 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003124 case EVENT_PROMPT_UNVALIDATED: {
3125 handlePromptUnvalidated((Network) msg.obj);
3126 break;
3127 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003128 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3129 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003130 break;
3131 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003132 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3133 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3134 mKeepaliveTracker.handleStartKeepalive(msg);
3135 break;
3136 }
3137 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3138 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3139 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3140 int slot = msg.arg1;
3141 int reason = msg.arg2;
3142 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3143 break;
3144 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003145 case EVENT_SYSTEM_READY: {
3146 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3147 nai.networkMonitor.systemReady = true;
3148 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003149 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003150 break;
3151 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003152 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003153 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003154 break;
3155 }
Erik Klinea24d4592018-01-11 21:07:29 +09003156 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3157 handlePrivateDnsSettingsChanged();
3158 break;
dalyk7301aa42018-03-05 12:42:22 -05003159 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3160 handlePrivateDnsValidationUpdate(
3161 (PrivateDnsValidationUpdate) msg.obj);
3162 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 }
3164 }
3165 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003166
3167 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003168 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003169 public int tether(String iface, String callerPkg) {
3170 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003171 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003172 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003173 } else {
3174 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3175 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003176 }
3177
3178 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003179 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003180 public int untether(String iface, String callerPkg) {
3181 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003182
3183 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003184 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003185 } else {
3186 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3187 }
3188 }
3189
3190 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003191 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003192 public int getLastTetherError(String iface) {
3193 enforceTetherAccessPermission();
3194
3195 if (isTetheringSupported()) {
3196 return mTethering.getLastTetherError(iface);
3197 } else {
3198 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3199 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003200 }
3201
3202 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003203 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003204 public String[] getTetherableUsbRegexs() {
3205 enforceTetherAccessPermission();
3206 if (isTetheringSupported()) {
3207 return mTethering.getTetherableUsbRegexs();
3208 } else {
3209 return new String[0];
3210 }
3211 }
3212
Lorenzo Colitti18660282016-07-04 12:55:44 +09003213 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003214 public String[] getTetherableWifiRegexs() {
3215 enforceTetherAccessPermission();
3216 if (isTetheringSupported()) {
3217 return mTethering.getTetherableWifiRegexs();
3218 } else {
3219 return new String[0];
3220 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003221 }
3222
Lorenzo Colitti18660282016-07-04 12:55:44 +09003223 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003224 public String[] getTetherableBluetoothRegexs() {
3225 enforceTetherAccessPermission();
3226 if (isTetheringSupported()) {
3227 return mTethering.getTetherableBluetoothRegexs();
3228 } else {
3229 return new String[0];
3230 }
3231 }
3232
Lorenzo Colitti18660282016-07-04 12:55:44 +09003233 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003234 public int setUsbTethering(boolean enable, String callerPkg) {
3235 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003236 if (isTetheringSupported()) {
3237 return mTethering.setUsbTethering(enable);
3238 } else {
3239 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3240 }
3241 }
3242
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003243 // TODO - move iface listing, queries, etc to new module
3244 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003245 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003246 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003247 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003248 return mTethering.getTetherableIfaces();
3249 }
3250
Lorenzo Colitti18660282016-07-04 12:55:44 +09003251 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003252 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003253 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003254 return mTethering.getTetheredIfaces();
3255 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003256
Lorenzo Colitti18660282016-07-04 12:55:44 +09003257 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003258 public String[] getTetheringErroredIfaces() {
3259 enforceTetherAccessPermission();
3260 return mTethering.getErroredIfaces();
3261 }
3262
Lorenzo Colitti18660282016-07-04 12:55:44 +09003263 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003264 public String[] getTetheredDhcpRanges() {
3265 enforceConnectivityInternalPermission();
3266 return mTethering.getTetheredDhcpRanges();
3267 }
3268
Udam Saini0e94c362017-06-07 12:06:28 -07003269 @Override
3270 public boolean isTetheringSupported(String callerPkg) {
3271 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3272 return isTetheringSupported();
3273 }
3274
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003275 // if ro.tether.denied = true we default to no tethering
3276 // gservices could set the secure setting to 1 though to enable it on a build where it
3277 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003278 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003279 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3280 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3281 Settings.Global.TETHER_SUPPORTED, defaultVal));
3282 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003283 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003284
3285 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3286 boolean adminUser = false;
3287 final long token = Binder.clearCallingIdentity();
3288 try {
3289 adminUser = mUserManager.isAdminUser();
3290 } finally {
3291 Binder.restoreCallingIdentity(token);
3292 }
3293
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003294 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003295 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003296
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003297 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003298 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3299 String callerPkg) {
3300 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003301 if (!isTetheringSupported()) {
3302 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3303 return;
3304 }
3305 mTethering.startTethering(type, receiver, showProvisioningUi);
3306 }
3307
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003308 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003309 public void stopTethering(int type, String callerPkg) {
3310 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003311 mTethering.stopTethering(type);
3312 }
3313
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003314 // Called when we lose the default network and have no replacement yet.
3315 // This will automatically be cleared after X seconds or a new default network
3316 // becomes CONNECTED, whichever happens first. The timer is started by the
3317 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003318 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003319 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003320 if (mNetTransitionWakeLock.isHeld()) {
3321 return;
3322 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003323 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003324 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3325 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003326 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003327 mWakelockLogs.log("ACQUIRE for " + forWhom);
3328 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3329 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003330 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003331
Hugo Benichi4c31b342017-03-30 23:18:10 +09003332 // Called when we gain a new default network to release the network transition wakelock in a
3333 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3334 // message is cancelled.
3335 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003336 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003337 if (!mNetTransitionWakeLock.isHeld()) {
3338 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003339 }
3340 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003341 // Cancel self timeout on wakelock hold.
3342 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3343 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3344 mHandler.sendMessageDelayed(msg, 1000);
3345 }
3346
3347 // Called when either message of ensureNetworkTransitionWakelock or
3348 // scheduleReleaseNetworkTransitionWakelock is processed.
3349 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3350 String event = eventName(eventId);
3351 synchronized (this) {
3352 if (!mNetTransitionWakeLock.isHeld()) {
3353 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3354 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3355 return;
3356 }
3357 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003358 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3359 mTotalWakelockDurationMs += lockDuration;
3360 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3361 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003362 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003363 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003364 }
3365
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003366 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003367 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003368 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003369 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003370 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003371 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003372 }
3373
Lorenzo Colitti18660282016-07-04 12:55:44 +09003374 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003375 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003376 enforceAccessPermission();
3377 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003378 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003379 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003380 mHandler.sendMessage(
3381 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3382 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003383
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003384 private void handleReportNetworkConnectivity(
3385 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003386 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003387 if (network == null) {
3388 nai = getDefaultNetwork();
3389 } else {
3390 nai = getNetworkAgentInfoForNetwork(network);
3391 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003392 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3393 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3394 return;
3395 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003396 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003397 if (hasConnectivity == nai.lastValidated) {
3398 return;
3399 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003400 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003401 int netid = nai.network.netId;
3402 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003403 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003404 // Validating a network that has not yet connected could result in a call to
3405 // rematchNetworkAndRequests() which is not meant to work on such networks.
3406 if (!nai.everConnected) {
3407 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003408 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003409 LinkProperties lp = getLinkProperties(nai);
3410 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3411 return;
3412 }
Erik Kline736353a2018-03-21 07:18:33 -07003413 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003414 }
3415
Lorenzo Colitti18660282016-07-04 12:55:44 +09003416 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003417 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003418 if (network == null) return mProxyTracker.getDefaultProxy();
3419 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003420 if (globalProxy != null) return globalProxy;
3421 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3422 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3423 // caller may not have.
3424 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3425 if (nai == null) return null;
3426 synchronized (nai) {
3427 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3428 if (proxyInfo == null) return null;
3429 return new ProxyInfo(proxyInfo);
3430 }
3431 }
3432
Chalard Jean3c443fc2018-06-07 18:37:59 +09003433 @Override
3434 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003435 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003436 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003437 }
3438
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003439 private void loadGlobalProxy() {
3440 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003441 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3442 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3443 String exclList = Settings.Global.getString(res,
3444 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003445 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3446 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003447 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003448 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003449 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003450 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003451 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003452 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003453 if (!proxyProperties.isValid()) {
3454 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3455 return;
3456 }
3457
Chalard Jean52c2aa72018-06-07 16:44:04 +09003458 synchronized (mProxyTracker.mProxyLock) {
3459 mProxyTracker.mGlobalProxy = proxyProperties;
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003460 }
3461 }
3462 }
3463
Chalard Jean5afbc832018-06-07 18:02:37 +09003464 @Override
3465 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003466 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003467 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003468 }
3469
Jason Monk207900c2014-04-25 15:00:09 -04003470 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003471 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003472 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003473 proxy = null;
3474 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003475 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 }
3477
Paul Jensene0bef712014-12-10 15:12:18 -05003478 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3479 // This method gets called when any network changes proxy, but the broadcast only ever contains
3480 // the default proxy (even if it hasn't changed).
3481 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3482 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003483 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003484 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3485 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3486
Chalard Jean4949dd72018-06-07 17:41:29 +09003487 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003488 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003489 }
3490 }
3491
Robert Greenwalt434203a2010-10-11 16:00:27 -07003492 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003493 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003494 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003495 if (!TextUtils.isEmpty(proxy)) {
3496 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003497 if (data.length == 0) {
3498 return;
3499 }
3500
Chalard Jean4133a122018-06-04 13:33:12 +09003501 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003502 int proxyPort = 8080;
3503 if (data.length > 1) {
3504 try {
3505 proxyPort = Integer.parseInt(data[1]);
3506 } catch (NumberFormatException e) {
3507 return;
3508 }
3509 }
Chalard Jean4133a122018-06-04 13:33:12 +09003510 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003511 setGlobalProxy(p);
3512 }
3513 }
3514
Robert Greenwalt434203a2010-10-11 16:00:27 -07003515 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003516 final private HashMap<Uri, Integer> mUriEventMap;
3517 final private Context mContext;
3518 final private Handler mHandler;
3519
3520 SettingsObserver(Context context, Handler handler) {
3521 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003522 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003523 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003524 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003525 }
3526
Erik Klineda4bfa82015-04-30 12:58:40 +09003527 void observe(Uri uri, int what) {
3528 mUriEventMap.put(uri, what);
3529 final ContentResolver resolver = mContext.getContentResolver();
3530 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 }
3532
3533 @Override
3534 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003535 Slog.wtf(TAG, "Should never be reached.");
3536 }
3537
3538 @Override
3539 public void onChange(boolean selfChange, Uri uri) {
3540 final Integer what = mUriEventMap.get(uri);
3541 if (what != null) {
3542 mHandler.obtainMessage(what.intValue()).sendToTarget();
3543 } else {
3544 loge("No matching event to send for URI=" + uri);
3545 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003546 }
3547 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003548
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003549 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003550 Slog.d(TAG, s);
3551 }
3552
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003553 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003554 Slog.e(TAG, s);
3555 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003556
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003557 private static void loge(String s, Throwable t) {
3558 Slog.e(TAG, s, t);
3559 }
3560
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003561 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003562 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003563 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3564 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3565 *
3566 * @param oldPackage Package name of the application which currently controls VPN, which will
3567 * be replaced. If there is no such application, this should should either be
3568 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3569 * @param newPackage Package name of the application which should gain control of VPN, or
3570 * {@code null} to disable.
3571 * @param userId User for whom to prepare the new VPN.
3572 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003573 * @hide
3574 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003575 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003576 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3577 int userId) {
3578 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003579
Hugo Benichi20035e02017-04-26 14:53:28 +09003580 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003581 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003582 Vpn vpn = mVpns.get(userId);
3583 if (vpn != null) {
3584 return vpn.prepare(oldPackage, newPackage);
3585 } else {
3586 return false;
3587 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003588 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003589 }
3590
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003591 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003592 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3593 * This method is used by system-privileged apps.
3594 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3595 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3596 *
3597 * @param packageName The package for which authorization state should change.
3598 * @param userId User for whom {@code packageName} is installed.
3599 * @param authorized {@code true} if this app should be able to start a VPN connection without
3600 * explicit user approval, {@code false} if not.
3601 *
Jeff Davidson05542602014-08-11 14:07:27 -07003602 * @hide
3603 */
3604 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003605 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3606 enforceCrossUserPermission(userId);
3607
Hugo Benichi20035e02017-04-26 14:53:28 +09003608 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003609 Vpn vpn = mVpns.get(userId);
3610 if (vpn != null) {
3611 vpn.setPackageAuthorization(packageName, authorized);
3612 }
Jeff Davidson05542602014-08-11 14:07:27 -07003613 }
3614 }
3615
3616 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003617 * Configure a TUN interface and return its file descriptor. Parameters
3618 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003619 * and not available in ConnectivityManager. Permissions are checked in
3620 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003621 * @hide
3622 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003623 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003624 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003625 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003626 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003627 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003628 return mVpns.get(user).establish(config);
3629 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003630 }
3631
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003632 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003633 * Start legacy VPN, controlling native daemons as needed. Creates a
3634 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003635 */
3636 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003637 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003638 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003639 final LinkProperties egress = getActiveLinkProperties();
3640 if (egress == null) {
3641 throw new IllegalStateException("Missing active network connection");
3642 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003643 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003644 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003645 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3646 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003647 }
3648
3649 /**
3650 * Return the information of the ongoing legacy VPN. This method is used
3651 * by VpnSettings and not available in ConnectivityManager. Permissions
3652 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003653 */
3654 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003655 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3656 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003657
Hugo Benichi20035e02017-04-26 14:53:28 +09003658 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003659 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003660 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003661 }
3662
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003663 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003664 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3665 * and not available in ConnectivityManager.
3666 */
3667 @Override
3668 public VpnInfo[] getAllVpnInfo() {
3669 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003670 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003671 if (mLockdownEnabled) {
3672 return new VpnInfo[0];
3673 }
3674
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003675 List<VpnInfo> infoList = new ArrayList<>();
3676 for (int i = 0; i < mVpns.size(); i++) {
3677 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3678 if (info != null) {
3679 infoList.add(info);
3680 }
3681 }
3682 return infoList.toArray(new VpnInfo[infoList.size()]);
3683 }
3684 }
3685
3686 /**
3687 * @return VPN information for accounting, or null if we can't retrieve all required
3688 * information, e.g primary underlying iface.
3689 */
3690 @Nullable
3691 private VpnInfo createVpnInfo(Vpn vpn) {
3692 VpnInfo info = vpn.getVpnInfo();
3693 if (info == null) {
3694 return null;
3695 }
3696 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3697 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3698 // the underlyingNetworks list.
3699 if (underlyingNetworks == null) {
3700 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3701 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3702 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3703 }
3704 } else if (underlyingNetworks.length > 0) {
3705 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3706 if (linkProperties != null) {
3707 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3708 }
3709 }
3710 return info.primaryUnderlyingIface == null ? null : info;
3711 }
3712
3713 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003714 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3715 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003716 * Permissions are checked in Vpn class.
3717 * @hide
3718 */
3719 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003720 public VpnConfig getVpnConfig(int userId) {
3721 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003722 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003723 Vpn vpn = mVpns.get(userId);
3724 if (vpn != null) {
3725 return vpn.getVpnConfig();
3726 } else {
3727 return null;
3728 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003729 }
3730 }
3731
Chalard Jean6b65ec72018-05-18 22:02:56 +09003732 /**
3733 * Ask all VPN objects to recompute and update their capabilities.
3734 *
3735 * When underlying networks change, VPNs may have to update capabilities to reflect things
3736 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3737 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3738 * handler thread through their agent, this is asynchronous. When the capabilities objects
3739 * are computed they will be up-to-date as they are computed synchronously from here and
3740 * this is running on the ConnectivityService thread.
3741 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3742 */
3743 private void updateAllVpnsCapabilities() {
3744 synchronized (mVpns) {
3745 for (int i = 0; i < mVpns.size(); i++) {
3746 final Vpn vpn = mVpns.valueAt(i);
3747 vpn.updateCapabilities();
3748 }
3749 }
3750 }
3751
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003752 @Override
3753 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003754 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3755 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3756 return false;
3757 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003758
Hugo Benichi69744342017-11-27 10:57:16 +09003759 synchronized (mVpns) {
3760 // Tear down existing lockdown if profile was removed
3761 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3762 if (mLockdownEnabled) {
3763 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3764 if (profileTag == null) {
3765 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3766 return false;
3767 }
3768 String profileName = new String(profileTag);
3769 final VpnProfile profile = VpnProfile.decode(
3770 profileName, mKeyStore.get(Credentials.VPN + profileName));
3771 if (profile == null) {
3772 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3773 setLockdownTracker(null);
3774 return true;
3775 }
3776 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003777 Vpn vpn = mVpns.get(user);
3778 if (vpn == null) {
3779 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3780 return false;
3781 }
3782 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003783 } else {
3784 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003785 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003786 }
3787
3788 return true;
3789 }
3790
3791 /**
3792 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3793 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3794 */
Hugo Benichi69744342017-11-27 10:57:16 +09003795 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003796 private void setLockdownTracker(LockdownVpnTracker tracker) {
3797 // Shutdown any existing tracker
3798 final LockdownVpnTracker existing = mLockdownTracker;
3799 mLockdownTracker = null;
3800 if (existing != null) {
3801 existing.shutdown();
3802 }
3803
Robin Leec3736bc2017-03-10 16:19:54 +00003804 if (tracker != null) {
3805 mLockdownTracker = tracker;
3806 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003807 }
3808 }
3809
Hugo Benichi69744342017-11-27 10:57:16 +09003810 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003811 private void throwIfLockdownEnabled() {
3812 if (mLockdownEnabled) {
3813 throw new IllegalStateException("Unavailable in lockdown mode");
3814 }
3815 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003816
Robin Lee244ce8e2016-01-05 18:03:46 +00003817 /**
Robin Lee17e61832016-05-09 13:46:28 +01003818 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3819 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003820 *
Robin Lee17e61832016-05-09 13:46:28 +01003821 * @return {@code true} if the service was started, the service was already connected, or there
3822 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003823 */
Robin Lee17e61832016-05-09 13:46:28 +01003824 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003825 synchronized (mVpns) {
3826 Vpn vpn = mVpns.get(userId);
3827 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003828 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003829 // exists already.
3830 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3831 return false;
3832 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003833
Robin Lee812800c2016-05-13 15:38:08 +01003834 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003835 }
3836 }
3837
3838 @Override
Charles He36738632017-05-15 17:07:18 +01003839 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3840 enforceSettingsPermission();
3841 enforceCrossUserPermission(userId);
3842
3843 synchronized (mVpns) {
3844 Vpn vpn = mVpns.get(userId);
3845 if (vpn == null) {
3846 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3847 return false;
3848 }
3849 return vpn.isAlwaysOnPackageSupported(packageName);
3850 }
3851 }
3852
3853 @Override
Robin Leedc679712016-05-03 13:23:03 +01003854 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 enforceConnectivityInternalPermission();
3856 enforceCrossUserPermission(userId);
3857
Robin Lee244ce8e2016-01-05 18:03:46 +00003858 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003859 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3860 if (LockdownVpnTracker.isEnabled()) {
3861 return false;
3862 }
3863
Robin Lee244ce8e2016-01-05 18:03:46 +00003864 Vpn vpn = mVpns.get(userId);
3865 if (vpn == null) {
3866 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3867 return false;
3868 }
Robin Lee17e61832016-05-09 13:46:28 +01003869 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003870 return false;
3871 }
Robin Lee17e61832016-05-09 13:46:28 +01003872 if (!startAlwaysOnVpn(userId)) {
3873 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003874 return false;
3875 }
3876 }
3877 return true;
3878 }
3879
3880 @Override
3881 public String getAlwaysOnVpnPackage(int userId) {
3882 enforceConnectivityInternalPermission();
3883 enforceCrossUserPermission(userId);
3884
3885 synchronized (mVpns) {
3886 Vpn vpn = mVpns.get(userId);
3887 if (vpn == null) {
3888 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3889 return null;
3890 }
3891 return vpn.getAlwaysOnPackage();
3892 }
3893 }
3894
Wink Savilleab9321d2013-06-29 21:10:57 -07003895 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003896 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003897 // TODO: Remove? Any reason to trigger a provisioning check?
3898 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003899 }
3900
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003901 /** Location to an updatable file listing carrier provisioning urls.
3902 * An example:
3903 *
3904 * <?xml version="1.0" encoding="utf-8"?>
3905 * <provisioningUrls>
3906 * <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 -07003907 * </provisioningUrls>
3908 */
3909 private static final String PROVISIONING_URL_PATH =
3910 "/data/misc/radio/provisioning_urls.xml";
3911 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003912
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003913 /** XML tag for root element. */
3914 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3915 /** XML tag for individual url */
3916 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003917 /** XML attribute for mcc */
3918 private static final String ATTR_MCC = "mcc";
3919 /** XML attribute for mnc */
3920 private static final String ATTR_MNC = "mnc";
3921
Paul Jensen434dde82015-06-11 09:43:30 -04003922 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003923 FileReader fileReader = null;
3924 XmlPullParser parser = null;
3925 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003926
3927 try {
3928 fileReader = new FileReader(mProvisioningUrlFile);
3929 parser = Xml.newPullParser();
3930 parser.setInput(fileReader);
3931 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3932
3933 while (true) {
3934 XmlUtils.nextElement(parser);
3935
3936 String element = parser.getName();
3937 if (element == null) break;
3938
Paul Jensen434dde82015-06-11 09:43:30 -04003939 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003940 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3941 try {
3942 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3943 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3944 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3945 parser.next();
3946 if (parser.getEventType() == XmlPullParser.TEXT) {
3947 return parser.getText();
3948 }
3949 }
3950 }
3951 } catch (NumberFormatException e) {
3952 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3953 }
3954 }
3955 }
3956 return null;
3957 } catch (FileNotFoundException e) {
3958 loge("Carrier Provisioning Urls file not found");
3959 } catch (XmlPullParserException e) {
3960 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3961 } catch (IOException e) {
3962 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3963 } finally {
3964 if (fileReader != null) {
3965 try {
3966 fileReader.close();
3967 } catch (IOException e) {}
3968 }
3969 }
3970 return null;
3971 }
3972
Wink Saville42d4f082013-07-20 20:31:59 -07003973 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003974 public String getMobileProvisioningUrl() {
3975 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003976 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003977 if (TextUtils.isEmpty(url)) {
3978 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003979 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003980 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003981 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003982 }
Wink Saville8cf35602013-07-10 23:00:07 -07003983 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003984 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003985 String phoneNumber = mTelephonyManager.getLine1Number();
3986 if (TextUtils.isEmpty(phoneNumber)) {
3987 phoneNumber = "0000000000";
3988 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003989 url = String.format(url,
3990 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3991 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09003992 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003993 }
3994
Wink Savilleab9321d2013-06-29 21:10:57 -07003995 return url;
3996 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003997
Wink Saville948282b2013-08-29 08:55:16 -07003998 @Override
3999 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004000 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004001 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004002 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4003 return;
4004 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004005 final long ident = Binder.clearCallingIdentity();
4006 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004007 // Concatenate the range of types onto the range of NetIDs.
4008 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4009 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004010 } finally {
4011 Binder.restoreCallingIdentity(ident);
4012 }
Wink Saville948282b2013-08-29 08:55:16 -07004013 }
Wink Saville7788c612013-08-29 14:57:08 -07004014
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004015 @Override
4016 public void setAirplaneMode(boolean enable) {
4017 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004018 final long ident = Binder.clearCallingIdentity();
4019 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004020 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004021 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004022 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4023 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004024 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004025 } finally {
4026 Binder.restoreCallingIdentity(ident);
4027 }
4028 }
4029
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004030 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004031 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004032 Vpn userVpn = mVpns.get(userId);
4033 if (userVpn != null) {
4034 loge("Starting user already has a VPN");
4035 return;
4036 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004037 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004038 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004039 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4040 updateLockdownVpn();
4041 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004042 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004043 }
4044
4045 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004046 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004047 Vpn userVpn = mVpns.get(userId);
4048 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004049 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004050 return;
4051 }
Robin Lee17e61832016-05-09 13:46:28 +01004052 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004053 mVpns.delete(userId);
4054 }
4055 }
4056
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004057 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004058 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004059 final int vpnsSize = mVpns.size();
4060 for (int i = 0; i < vpnsSize; i++) {
4061 Vpn vpn = mVpns.valueAt(i);
4062 vpn.onUserAdded(userId);
4063 }
4064 }
4065 }
4066
4067 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004068 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004069 final int vpnsSize = mVpns.size();
4070 for (int i = 0; i < vpnsSize; i++) {
4071 Vpn vpn = mVpns.valueAt(i);
4072 vpn.onUserRemoved(userId);
4073 }
4074 }
4075 }
4076
Robin Lee89e7a692016-02-29 14:38:17 +00004077 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004078 synchronized (mVpns) {
4079 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4080 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4081 updateLockdownVpn();
4082 } else {
4083 startAlwaysOnVpn(userId);
4084 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004085 }
4086 }
4087
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004088 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4089 @Override
4090 public void onReceive(Context context, Intent intent) {
4091 final String action = intent.getAction();
4092 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4093 if (userId == UserHandle.USER_NULL) return;
4094
Robin Lee323f29d2016-05-04 16:38:06 +01004095 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004096 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004097 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004098 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004099 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4100 onUserAdded(userId);
4101 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4102 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004103 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4104 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004105 }
4106 }
4107 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004108
Robin Lee95204e02017-01-27 11:59:22 +00004109 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4110 @Override
4111 public void onReceive(Context context, Intent intent) {
4112 // Try creating lockdown tracker, since user present usually means
4113 // unlocked keystore.
4114 updateLockdownVpn();
4115 mContext.unregisterReceiver(this);
4116 }
4117 };
4118
Chalard Jean4133a122018-06-04 13:33:12 +09004119 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4120 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004121
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004122 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4123 // Map from UID to number of NetworkRequests that UID has filed.
4124 @GuardedBy("mUidToNetworkRequestCount")
4125 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4126
Robert Greenwalta67be032014-05-16 15:49:14 -07004127 private static class NetworkFactoryInfo {
4128 public final String name;
4129 public final Messenger messenger;
4130 public final AsyncChannel asyncChannel;
4131
4132 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4133 this.name = name;
4134 this.messenger = messenger;
4135 this.asyncChannel = asyncChannel;
4136 }
4137 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004138
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004139 private void ensureNetworkRequestHasType(NetworkRequest request) {
4140 if (request.type == NetworkRequest.Type.NONE) {
4141 throw new IllegalArgumentException(
4142 "All NetworkRequests in ConnectivityService must have a type");
4143 }
4144 }
4145
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004146 /**
4147 * Tracks info about the requester.
4148 * Also used to notice when the calling process dies so we can self-expire
4149 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004152 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004153 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 final int mPid;
4156 final int mUid;
4157 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004159 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004160 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004161 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004162 mPendingIntent = pi;
4163 messenger = null;
4164 mBinder = null;
4165 mPid = getCallingPid();
4166 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004167 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168 }
4169
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004170 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 super();
4172 messenger = m;
4173 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004174 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 mBinder = binder;
4176 mPid = getCallingPid();
4177 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004179 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180
4181 try {
4182 mBinder.linkToDeath(this, 0);
4183 } catch (RemoteException e) {
4184 binderDied();
4185 }
4186 }
4187
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004188 private void enforceRequestCountLimit() {
4189 synchronized (mUidToNetworkRequestCount) {
4190 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4191 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004192 throw new ServiceSpecificException(
4193 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004194 }
4195 mUidToNetworkRequestCount.put(mUid, networkRequests);
4196 }
4197 }
4198
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 if (mBinder != null) {
4201 mBinder.unlinkToDeath(this, 0);
4202 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004203 }
4204
4205 public void binderDied() {
4206 log("ConnectivityService NetworkRequestInfo binderDied(" +
4207 request + ", " + mBinder + ")");
4208 releaseNetworkRequest(request);
4209 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004210
4211 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004212 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004214 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004215 }
4216
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004217 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4218 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4219 if (badCapability != null) {
4220 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004221 }
4222 }
4223
Chalard Jeanb03a6222018-04-11 21:09:10 +09004224 // This checks that the passed capabilities either do not request a specific SSID, or the
4225 // calling app has permission to do so.
4226 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4227 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004228 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004229 throw new SecurityException("Insufficient permissions to request a specific SSID");
4230 }
4231 }
4232
Erik Kline9d598e12015-07-13 16:37:51 +09004233 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004234 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004235 synchronized (nai) {
4236 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4237 if (nri.request.networkCapabilities.hasSignalStrength() &&
4238 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4239 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4240 }
4241 }
4242 }
Chalard Jean4133a122018-06-04 13:33:12 +09004243 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004244 }
4245
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004246 private void updateSignalStrengthThresholds(
4247 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4248 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004249 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004250 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4251
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004252 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004253 String detail;
4254 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4255 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4256 } else {
4257 detail = reason;
4258 }
4259 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4260 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4261 }
4262
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004263 nai.asyncChannel.sendMessage(
4264 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004265 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004266 }
4267
Etan Cohen859748f2017-04-03 17:42:34 -07004268 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4269 if (nc == null) {
4270 return;
4271 }
4272 NetworkSpecifier ns = nc.getNetworkSpecifier();
4273 if (ns == null) {
4274 return;
4275 }
4276 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4277 ns.assertValidFromUid(Binder.getCallingUid());
4278 }
4279
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 @Override
4281 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004282 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004283 final NetworkRequest.Type type = (networkCapabilities == null)
4284 ? NetworkRequest.Type.TRACK_DEFAULT
4285 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004286 // If the requested networkCapabilities is null, take them instead from
4287 // the default network request. This allows callers to keep track of
4288 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004289 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004290 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004291 enforceAccessPermission();
4292 } else {
4293 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4294 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004295 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4296 // of the app when the request is filed, but we never change the request if the app
4297 // changes network state. http://b/29964605
4298 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004299 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004300 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004301 ensureSufficientPermissionsForRequest(networkCapabilities,
4302 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004303 // Set the UID range for this request to the single UID of the requester, or to an empty
4304 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004305 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4306 // are no visible methods to set the UIDs, an app could use reflection to try and get
4307 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004308 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004309
Etan Cohenba07c8c2017-02-05 10:42:27 -08004310 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311 throw new IllegalArgumentException("Bad timeout specified");
4312 }
Etan Cohen859748f2017-04-03 17:42:34 -07004313 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004314
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004315 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004316 nextNetworkRequestId(), type);
4317 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004318 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319
4320 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004321 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004323 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004324 }
4325 return networkRequest;
4326 }
4327
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004328 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004329 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004330 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004331 } else {
4332 enforceChangePermission();
4333 }
4334 }
4335
fenglub15e72b2015-03-20 11:29:56 -07004336 @Override
fengludb571472015-04-21 17:12:05 -07004337 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004338 enforceAccessPermission();
4339 NetworkAgentInfo nai = null;
4340 if (network == null) {
4341 return false;
4342 }
4343 synchronized (mNetworkForNetId) {
4344 nai = mNetworkForNetId.get(network.netId);
4345 }
4346 if (nai != null) {
4347 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004348 synchronized (mBandwidthRequests) {
4349 final int uid = Binder.getCallingUid();
4350 Integer uidReqs = mBandwidthRequests.get(uid);
4351 if (uidReqs == null) {
4352 uidReqs = new Integer(0);
4353 }
4354 mBandwidthRequests.put(uid, ++uidReqs);
4355 }
fenglub15e72b2015-03-20 11:29:56 -07004356 return true;
4357 }
4358 return false;
4359 }
4360
Felipe Lemeee27cab2016-06-20 16:36:29 -07004361 private boolean isSystem(int uid) {
4362 return uid < Process.FIRST_APPLICATION_UID;
4363 }
fenglub15e72b2015-03-20 11:29:56 -07004364
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004365 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004366 final int uid = Binder.getCallingUid();
4367 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004368 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004369 return;
4370 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004371 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4372 // Policy already enforced.
4373 return;
4374 }
4375 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4376 // If UID is restricted, don't allow them to bring up metered APNs.
4377 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004378 }
4379 }
4380
Robert Greenwalt9258c642014-03-26 16:47:06 -07004381 @Override
4382 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4383 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004384 checkNotNull(operation, "PendingIntent cannot be null.");
4385 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4386 enforceNetworkRequestPermissions(networkCapabilities);
4387 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004388 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004389 ensureSufficientPermissionsForRequest(networkCapabilities,
4390 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004391 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004392 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004393
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004394 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004395 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4396 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004397 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004398 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4399 nri));
4400 return networkRequest;
4401 }
4402
Jeremy Joslin79294842014-12-03 17:15:28 -08004403 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4404 mHandler.sendMessageDelayed(
4405 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4406 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4407 }
4408
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004409 @Override
4410 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004411 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004412 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4413 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004414 }
4415
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004416 // In order to implement the compatibility measure for pre-M apps that call
4417 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4418 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4419 // This ensures it has permission to do so.
4420 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4421 if (nc == null) {
4422 return false;
4423 }
4424 int[] transportTypes = nc.getTransportTypes();
4425 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4426 return false;
4427 }
4428 try {
4429 mContext.enforceCallingOrSelfPermission(
4430 android.Manifest.permission.ACCESS_WIFI_STATE,
4431 "ConnectivityService");
4432 } catch (SecurityException e) {
4433 return false;
4434 }
4435 return true;
4436 }
4437
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 @Override
4439 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4440 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004441 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4442 enforceAccessPermission();
4443 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004444
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004445 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004446 ensureSufficientPermissionsForRequest(networkCapabilities,
4447 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004448 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004449 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4450 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4451 // onLost and onAvailable callbacks when networks move in and out of the background.
4452 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4453 // can't request networks.
4454 restrictBackgroundRequestForCaller(nc);
4455 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004456
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004457 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004458 NetworkRequest.Type.LISTEN);
4459 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004460 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004461
4462 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4463 return networkRequest;
4464 }
4465
4466 @Override
4467 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4468 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004469 checkNotNull(operation, "PendingIntent cannot be null.");
4470 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4471 enforceAccessPermission();
4472 }
Etan Cohen859748f2017-04-03 17:42:34 -07004473 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004474 ensureSufficientPermissionsForRequest(networkCapabilities,
4475 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004476
Chalard Jeandda156a2018-01-10 21:19:32 +09004477 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004478 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004479
4480 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004481 NetworkRequest.Type.LISTEN);
4482 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004483 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004484
4485 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004486 }
4487
Erik Klineacdd6392016-07-07 16:50:58 +09004488 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004489 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004490 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004491 mHandler.sendMessage(mHandler.obtainMessage(
4492 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004493 }
4494
4495 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004496 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004497 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004498 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4499 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004500 }
4501
Robert Greenwalta67be032014-05-16 15:49:14 -07004502 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004503 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004504 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4505 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4506 }
4507
4508 @Override
4509 public void unregisterNetworkFactory(Messenger messenger) {
4510 enforceConnectivityInternalPermission();
4511 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4512 }
4513
4514 private void handleUnregisterNetworkFactory(Messenger messenger) {
4515 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4516 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004517 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004518 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004520 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004521 }
4522
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 /**
4524 * NetworkAgentInfo supporting a request by requestId.
4525 * These have already been vetted (their Capabilities satisfy the request)
4526 * and the are the highest scored network available.
4527 * the are keyed off the Requests requestId.
4528 */
Hugo Benichicd952782017-09-20 11:20:14 +09004529 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4530 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004531 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532
Paul Jensen31a94f42015-02-13 14:18:39 -05004533 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4534 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004535 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004536 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4537 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4538 // there may not be a strict 1:1 correlation between the two.
4539 @GuardedBy("mNetworkForNetId")
4540 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004541
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 // NetworkAgentInfo keyed off its connecting messenger
4543 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004544 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004545 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004547 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004548 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004549
Paul Jensen2c311d62014-11-17 12:34:51 -05004550 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004552
Erik Klineda4bfa82015-04-30 12:58:40 +09004553 // Request used to optionally keep mobile data active even when higher
4554 // priority networks like Wi-Fi are active.
4555 private final NetworkRequest mDefaultMobileDataRequest;
4556
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004557 // Request used to optionally keep wifi data active even when higher
4558 // priority networks like ethernet are active.
4559 private final NetworkRequest mDefaultWifiRequest;
4560
Hugo Benichicd952782017-09-20 11:20:14 +09004561 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4562 synchronized (mNetworkForRequestId) {
4563 return mNetworkForRequestId.get(requestId);
4564 }
4565 }
4566
4567 private void clearNetworkForRequest(int requestId) {
4568 synchronized (mNetworkForRequestId) {
4569 mNetworkForRequestId.remove(requestId);
4570 }
4571 }
4572
4573 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4574 synchronized (mNetworkForRequestId) {
4575 mNetworkForRequestId.put(requestId, nai);
4576 }
4577 }
4578
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004579 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004580 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004581 }
4582
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004583 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004584 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004585 }
4586
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004587 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4588 return nri.request.requestId == mDefaultRequest.requestId;
4589 }
4590
Paul Jensen31a94f42015-02-13 14:18:39 -05004591 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004592 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004593 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004594 enforceConnectivityInternalPermission();
4595
Rubin Xu1bb5c082017-09-05 18:40:49 +01004596 LinkProperties lp = new LinkProperties(linkProperties);
4597 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004598 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4599 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004600 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004601 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004602 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004603 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004604 // Make sure the network capabilities reflect what the agent info says.
4605 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004606 synchronized (this) {
4607 nai.networkMonitor.systemReady = mSystemReady;
4608 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004609 final String extraInfo = networkInfo.getExtraInfo();
4610 final String name = TextUtils.isEmpty(extraInfo)
4611 ? nai.networkCapabilities.getSSID() : extraInfo;
4612 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004613 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004614 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004615 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004616 }
4617
Erik Klinee5dac902018-03-04 21:01:01 +09004618 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004620 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004621 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004622 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004623 }
Erik Klinee5dac902018-03-04 21:01:01 +09004624 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4625 NetworkInfo networkInfo = nai.networkInfo;
4626 nai.networkInfo = null;
4627 updateNetworkInfo(nai, networkInfo);
4628 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004629 }
4630
4631 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004632 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004633 int netId = networkAgent.network.netId;
4634
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004635 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4636 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004637 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004638 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004639 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004640
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004641 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 updateMtu(newLp, oldLp);
4643 // TODO - figure out what to do for clat
4644// for (LinkProperties lp : newLp.getStackedLinks()) {
4645// updateMtu(lp, null);
4646// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004647 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004648
Erik Kline94887872016-04-05 13:30:49 +09004649 updateRoutes(newLp, oldLp, netId);
4650 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004651 // Make sure LinkProperties represents the latest private DNS status.
4652 // This does not need to be done before updateDnses because the
4653 // LinkProperties are not the source of the private DNS configuration.
4654 // updateDnses will fetch the private DNS configuration from DnsManager.
4655 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004656
Hugo Benichi6f62b732017-06-27 15:13:20 +09004657 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004658 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004659 if (isDefaultNetwork(networkAgent)) {
4660 handleApplyDefaultProxy(newLp.getHttpProxy());
4661 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004662 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004663 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004664 // TODO - move this check to cover the whole function
4665 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004666 synchronized (networkAgent) {
4667 networkAgent.linkProperties = newLp;
4668 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004669 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004670 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4671 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004672
4673 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004674 }
4675
Joel Scherpelz668370b2017-06-08 15:35:21 +09004676 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004677 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004678 // marks on unsupported interfaces is harmless.
4679 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4680 return;
4681 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004682
Joel Scherpelz668370b2017-06-08 15:35:21 +09004683 int mark = mContext.getResources().getInteger(
4684 com.android.internal.R.integer.config_networkWakeupPacketMark);
4685 int mask = mContext.getResources().getInteger(
4686 com.android.internal.R.integer.config_networkWakeupPacketMask);
4687
4688 // Mask/mark of zero will not detect anything interesting.
4689 // Don't install rules unless both values are nonzero.
4690 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004691 return;
4692 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004693
4694 final String prefix = "iface:" + iface;
4695 try {
4696 if (add) {
4697 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4698 } else {
4699 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4700 }
4701 } catch (Exception e) {
4702 loge("Exception modifying wakeup packet monitoring: " + e);
4703 }
4704
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004705 }
4706
4707 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4708 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004709 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004710 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4711 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004712 for (String iface : interfaceDiff.added) {
4713 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004714 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004715 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004716 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004717 } catch (Exception e) {
4718 loge("Exception adding interface: " + e);
4719 }
4720 }
4721 for (String iface : interfaceDiff.removed) {
4722 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004723 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004724 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004725 mNetd.removeInterfaceFromNetwork(iface, netId);
4726 } catch (Exception e) {
4727 loge("Exception removing interface: " + e);
4728 }
4729 }
4730 }
4731
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004732 /**
4733 * Have netd update routes from oldLp to newLp.
4734 * @return true if routes changed between oldLp and newLp
4735 */
4736 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004737 // Compare the route diff to determine which routes should be added and removed.
4738 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4739 oldLp != null ? oldLp.getAllRoutes() : null,
4740 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004741
4742 // add routes before removing old in case it helps with continuous connectivity
4743
Chalard Jean4d660112018-06-04 16:52:49 +09004744 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004745 for (RouteInfo route : routeDiff.added) {
4746 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004747 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004748 try {
4749 mNetd.addRoute(netId, route);
4750 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004751 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4752 loge("Exception in addRoute for non-gateway: " + e);
4753 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 }
4755 }
4756 for (RouteInfo route : routeDiff.added) {
4757 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004758 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 try {
4760 mNetd.addRoute(netId, route);
4761 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004762 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4763 loge("Exception in addRoute for gateway: " + e);
4764 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 }
4766 }
4767
4768 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004769 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 try {
4771 mNetd.removeRoute(netId, route);
4772 } catch (Exception e) {
4773 loge("Exception in removeRoute: " + e);
4774 }
4775 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004776 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 }
Erik Kline41368502015-06-17 13:19:54 +09004778
Erik Kline94887872016-04-05 13:30:49 +09004779 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4780 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4781 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004782 }
Erik Kline94887872016-04-05 13:30:49 +09004783
Erik Kline1742fe12017-12-13 19:40:49 +09004784 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4785 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4786
Erik Klinea24d4592018-01-11 21:07:29 +09004787 if (DBG) {
4788 final Collection<InetAddress> dnses = newLp.getDnsServers();
4789 log("Setting DNS servers for network " + netId + " to " + dnses);
4790 }
Erik Kline94887872016-04-05 13:30:49 +09004791 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004792 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004793 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004794 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004795 }
Erik Kline4edba012017-04-07 15:29:29 +09004796 }
4797
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004798 private String getNetworkPermission(NetworkCapabilities nc) {
4799 // TODO: make these permission strings AIDL constants instead.
4800 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4801 return NetworkManagementService.PERMISSION_SYSTEM;
4802 }
4803 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4804 return NetworkManagementService.PERMISSION_NETWORK;
4805 }
4806 return null;
4807 }
4808
Paul Jensen3d194ea2015-06-16 14:27:36 -04004809 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004810 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4811 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4812 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004813 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004815 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004816 // Don't complain for VPNs since they're not driven by requests and there is no risk of
4817 // causing a connect/teardown loop.
4818 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
4819 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004820 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004821 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004822 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4823 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004824 // does not cause any request (that is not a listen) currently matching that agent to
4825 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004827 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004828 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004829 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004830 }
4831
Paul Jensen3d194ea2015-06-16 14:27:36 -04004832 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004834 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004835 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004836 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004837 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004838 }
Paul Jensene0988542015-06-25 15:30:08 -04004839 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004840 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004841 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004842 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004843 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004844 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004845 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004846 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004847 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004849 if (nai.isSuspended()) {
4850 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4851 } else {
4852 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4853 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004854
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004855 return newNc;
4856 }
4857
4858 /**
4859 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4860 *
4861 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4862 * capabilities we manage and store in {@code nai}, such as validated status and captive
4863 * portal status)
4864 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4865 * potentially triggers rematches.
4866 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4867 * change.)
4868 *
4869 * @param oldScore score of the network before any of the changes that prompted us
4870 * to call this function.
4871 * @param nai the network having its capabilities updated.
4872 * @param nc the new network capabilities.
4873 */
4874 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4875 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4876
4877 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004878
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004879 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004880 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004881 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004883 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004884 } catch (RemoteException e) {
4885 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004886 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004887 }
4888
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004889 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004890 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004891 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004893 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004894
Chalard Jeanf213ca12018-01-16 18:43:05 +09004895 updateUids(nai, prevNc, newNc);
4896
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004897 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004898 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4899 // the change we're processing can't affect any requests, it can only affect the listens
4900 // on this network. We might have been called by rematchNetworkAndRequests when a
4901 // network changed foreground state.
4902 processListenRequests(nai, true);
4903 } else {
4904 // If the requestable capabilities have changed or the score changed, we can't have been
4905 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004906 rematchAllNetworksAndRequests(nai, oldScore);
4907 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004908 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004909
4910 // Report changes that are interesting for network statistics tracking.
4911 if (prevNc != null) {
4912 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004913 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004914 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004915 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004916 if (meteredChanged || roamingChanged) {
4917 notifyIfacesChangedForNetworkStats();
4918 }
4919 }
4920
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004921 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004922 // Tell VPNs about updated capabilities, since they may need to
4923 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004924 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004925 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926 }
4927
Chalard Jeanf213ca12018-01-16 18:43:05 +09004928 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4929 NetworkCapabilities newNc) {
4930 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4931 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4932 if (null == prevRanges) prevRanges = new ArraySet<>();
4933 if (null == newRanges) newRanges = new ArraySet<>();
4934 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4935
4936 prevRanges.removeAll(newRanges);
4937 newRanges.removeAll(prevRangesCopy);
4938
4939 try {
4940 if (!newRanges.isEmpty()) {
4941 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4942 newRanges.toArray(addedRangesArray);
4943 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4944 }
4945 if (!prevRanges.isEmpty()) {
4946 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4947 prevRanges.toArray(removedRangesArray);
4948 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4949 }
4950 } catch (Exception e) {
4951 // Never crash!
4952 loge("Exception in updateUids: " + e);
4953 }
4954 }
4955
Hugo Benichief502882017-09-01 01:23:32 +00004956 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004957 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004958 // Ignore updates for disconnected networks
4959 return;
4960 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004961 // newLp is already a defensive copy.
4962 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004963 if (VDBG) {
4964 log("Update of LinkProperties for " + nai.name() +
4965 "; created=" + nai.created +
4966 "; everConnected=" + nai.everConnected);
4967 }
4968 LinkProperties oldLp = nai.linkProperties;
4969 synchronized (nai) {
4970 nai.linkProperties = newLp;
4971 }
4972 if (nai.everConnected) {
4973 updateLinkProperties(nai, oldLp);
4974 }
4975 }
4976
Paul Jensenc8b9a742014-09-30 15:37:41 -04004977 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004978 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4979 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004980 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004981 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004982 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4983 }
4984 }
4985
Robert Greenwalt7b816022014-04-18 15:25:25 -07004986 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4987 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004988 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004989 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4990 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004991 }
4992 }
4993
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004994 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4995 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004996 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004997 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004998 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4999 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005000 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005001 sendIntent(nri.mPendingIntent, intent);
5002 }
5003 // else not handled
5004 }
5005
5006 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5007 mPendingIntentWakeLock.acquire();
5008 try {
5009 if (DBG) log("Sending " + pendingIntent);
5010 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5011 } catch (PendingIntent.CanceledException e) {
5012 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5013 mPendingIntentWakeLock.release();
5014 releasePendingNetworkRequest(pendingIntent);
5015 }
5016 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5017 }
5018
5019 @Override
5020 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5021 String resultData, Bundle resultExtras) {
5022 if (DBG) log("Finished sending " + pendingIntent);
5023 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005024 // Release with a delay so the receiving client has an opportunity to put in its
5025 // own request.
5026 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005027 }
5028
Chalard Jeanf19db372018-01-26 19:24:40 +09005029 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005030 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005031 if (nri.messenger == null) {
5032 return; // Default request has no msgr
5033 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005034 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005035 // TODO: check if defensive copies of data is needed.
5036 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005037 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005038 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5039 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005040 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005041 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005042 case ConnectivityManager.CALLBACK_AVAILABLE: {
5043 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5044 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5045 break;
5046 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005047 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005048 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005049 break;
5050 }
5051 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005052 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005053 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005054 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005055 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005056 break;
5057 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005058 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005059 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005060 break;
5061 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005062 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005063 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005064 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005065 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005066 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005067 String notification = ConnectivityManager.getCallbackName(notificationType);
5068 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005069 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005070 nri.messenger.send(msg);
5071 } catch (RemoteException e) {
5072 // may occur naturally in the race of binder death.
5073 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5074 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005075 }
5076
Hugo Benichidba33db2017-03-23 22:40:44 +09005077 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5078 bundle.putParcelable(t.getClass().getSimpleName(), t);
5079 }
5080
Paul Jensenc8b9a742014-09-30 15:37:41 -04005081 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005082 if (nai.numRequestNetworkRequests() != 0) {
5083 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5084 NetworkRequest nr = nai.requestAt(i);
5085 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005086 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005087 loge("Dead network still had at least " + nr);
5088 break;
5089 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005090 }
5091 nai.asyncChannel.disconnect();
5092 }
5093
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5095 if (oldNetwork == null) {
5096 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5097 return;
5098 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005099 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005100
5101 // If we get here it means that the last linger timeout for this network expired. So there
5102 // must be no other active linger timers, and we must stop lingering.
5103 oldNetwork.clearLingerState();
5104
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005105 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005106 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005107 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005108 } else {
5109 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005110 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5111 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005113 }
5114
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005115 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005116 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005117 setupDataActivityTracking(newNetwork);
5118 try {
5119 mNetd.setDefaultNetId(newNetwork.network.netId);
5120 } catch (Exception e) {
5121 loge("Exception setting default network :" + e);
5122 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005123
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005124 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005125 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005126 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005127 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005128 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005129 }
5130
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005131 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005132 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5133 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5134 NetworkRequest nr = nri.request;
5135 if (!nr.isListen()) continue;
5136 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5137 nai.removeRequest(nri.request.requestId);
5138 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5139 }
5140 }
5141
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005142 if (capabilitiesChanged) {
5143 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5144 }
5145
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005146 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5147 NetworkRequest nr = nri.request;
5148 if (!nr.isListen()) continue;
5149 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5150 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005151 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005152 }
5153 }
5154 }
5155
Paul Jensen2161a8e2014-09-11 11:00:39 -04005156 // Handles a network appearing or improving its score.
5157 //
5158 // - Evaluates all current NetworkRequests that can be
5159 // satisfied by newNetwork, and reassigns to newNetwork
5160 // any such requests for which newNetwork is the best.
5161 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005162 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005163 // needed. A network is needed if it is the best network for
5164 // one or more NetworkRequests, or if it is a VPN.
5165 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005166 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005167 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005168 //
5169 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5170 // networks that have no chance (i.e. even if validated)
5171 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005172 //
5173 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5174 // it does not remove NetworkRequests that other Networks could better satisfy.
5175 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5176 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5177 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005178 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005179 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005180 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5181 // performed to tear down unvalidated networks that have no chance (i.e. even if
5182 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005183 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005184 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005185 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005186 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005188 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005189
5190 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5191 final int score = newNetwork.getCurrentScore();
5192
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005193 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005194
Paul Jensen2161a8e2014-09-11 11:00:39 -04005195 // Find and migrate to this Network any NetworkRequests for
5196 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005197 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5198 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005199 NetworkCapabilities nc = newNetwork.networkCapabilities;
5200 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005201 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005202 // Process requests in the first pass and listens in the second pass. This allows us to
5203 // change a network's capabilities depending on which requests it has. This is only
5204 // correct if the change in capabilities doesn't affect whether the network satisfies
5205 // requests or not, and doesn't affect the network's score.
5206 if (nri.request.isListen()) continue;
5207
Hugo Benichicd952782017-09-20 11:20:14 +09005208 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005209 final boolean satisfies = newNetwork.satisfies(nri.request);
5210 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005211 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005212 log("Network " + newNetwork.name() + " was already satisfying" +
5213 " request " + nri.request.requestId + ". No change.");
5214 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005215 keep = true;
5216 continue;
5217 }
5218
5219 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005220 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005221 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 // next check if it's better than any current network we're using for
5223 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005224 if (VDBG) {
5225 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005226 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005227 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005228 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005229 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005230 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005231 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005232 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005233 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005234 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005235 affectedNetworks.add(currentNetwork);
5236 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005237 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005238 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005239 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005240 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005241 if (!newNetwork.addRequest(nri.request)) {
5242 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5243 }
5244 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005245 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005246 // Tell NetworkFactories about the new score, so they can stop
5247 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005248 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005249 // network. Think about if there is a way to reduce this. Push
5250 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005251 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005252 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005253 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005254 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005255 if (currentNetwork != null) {
5256 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5257 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 }
5259 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005260 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005261 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5262 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005263 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005264 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5265 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5266 // This means this code doesn't have to handle the case where "currentNetwork" no
5267 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5268 if (DBG) {
5269 log("Network " + newNetwork.name() + " stopped satisfying" +
5270 " request " + nri.request.requestId);
5271 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005272 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005273 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005274 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005275 sendUpdatedScoreToFactories(nri.request, 0);
5276 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005277 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5278 newNetwork.name() +
5279 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005280 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005281 // TODO: Technically, sending CALLBACK_LOST here is
5282 // incorrect if there is a replacement network currently
5283 // connected that can satisfy nri, which is a request
5284 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005285 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5286 // so this code is only incorrect for a network that loses
5287 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005288 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005289 }
5290 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005291 if (isNewDefault) {
5292 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005293 makeDefault(newNetwork);
5294 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005295 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005296 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005297 // Have a new default network, release the transition wakelock in
5298 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005299 }
5300
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005301 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5302 Slog.wtf(TAG, String.format(
5303 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005304 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005305 }
5306 if (newNetwork.getCurrentScore() != score) {
5307 Slog.wtf(TAG, String.format(
5308 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005309 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005310 }
5311
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005312 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005313 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5314 // If the network went from background to foreground or vice versa, we need to update
5315 // its foreground state. It is safe to do this after rematching the requests because
5316 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5317 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005318 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005319 } else {
5320 processListenRequests(newNetwork, false);
5321 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005322
Paul Jensencf4c2c62015-07-01 14:16:32 -04005323 // do this after the default net is switched, but
5324 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005325 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005326
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005327 // Linger any networks that are no longer needed. This should be done after sending the
5328 // available callback for newNetwork.
5329 for (NetworkAgentInfo nai : affectedNetworks) {
5330 updateLingerState(nai, now);
5331 }
5332 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5333 // does not need to be done in any particular order.
5334 updateLingerState(newNetwork, now);
5335
Paul Jensencf4c2c62015-07-01 14:16:32 -04005336 if (isNewDefault) {
5337 // Maintain the illusion: since the legacy API only
5338 // understands one network at a time, we must pretend
5339 // that the current default network disconnected before
5340 // the new one connected.
5341 if (oldDefaultNetwork != null) {
5342 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5343 oldDefaultNetwork, true);
5344 }
5345 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5346 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5347 notifyLockdownVpn(newNetwork);
5348 }
5349
Robert Greenwalt7b816022014-04-18 15:25:25 -07005350 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005351 // Notify battery stats service about this network, both the normal
5352 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005353 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005354 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005355 final IBatteryStats bs = BatteryStatsService.getService();
5356 final int type = newNetwork.networkInfo.getType();
5357
5358 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5359 bs.noteNetworkInterfaceType(baseIface, type);
5360 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5361 final String stackedIface = stacked.getInterfaceName();
5362 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005363 }
5364 } catch (RemoteException ignored) {
5365 }
5366
Robert Greenwalt152ed372014-12-17 17:19:53 -08005367 // This has to happen after the notifyNetworkCallbacks as that tickles each
5368 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005369 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005370 // and will generally do a dns request so they can ensureRouteToHost and if
5371 // they do that before the callbacks happen they'll use the default network.
5372 //
5373 // TODO: Is there still a race here? We send the broadcast
5374 // after sending the callback, but if the app can receive the
5375 // broadcast before the callback, it might still break.
5376 //
5377 // This *does* introduce a race where if the user uses the new api
5378 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5379 // they may get old info. Reverse this after the old startUsing api is removed.
5380 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005381 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5382 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005383 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005384 // legacy type tracker filters out repeat adds
5385 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5386 }
5387 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005388
5389 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5390 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5391 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5392 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5393 if (newNetwork.isVPN()) {
5394 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5395 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005396 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005397 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5398 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005399 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005400 if (nai.getLingerExpiry() > 0) {
5401 // This network has active linger timers and no requests, but is not
5402 // lingering. Linger it.
5403 //
5404 // One way (the only way?) this can happen if this network is unvalidated
5405 // and became unneeded due to another network improving its score to the
5406 // point where this network will no longer be able to satisfy any requests
5407 // even if it validates.
5408 updateLingerState(nai, now);
5409 } else {
5410 if (DBG) log("Reaping " + nai.name());
5411 teardownUnneededNetwork(nai);
5412 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005413 }
5414 }
5415 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005416 }
5417
Paul Jensen1c7ba022015-06-16 14:27:36 -04005418 /**
5419 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5420 * being disconnected.
5421 * @param changed If only one Network's score or capabilities have been modified since the last
5422 * time this function was called, pass this Network in this argument, otherwise pass
5423 * null.
5424 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5425 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5426 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5427 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5428 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005429 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005430 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005431 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5432 // to avoid the slowness. It is not simply enough to process just "changed", for
5433 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005434 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005435
5436 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5437 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5438 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005439 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005440 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005441 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005442 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005443 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5444 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5445 // Rematch higher scoring networks first to prevent requests first matching a lower
5446 // scoring network and then a higher scoring network, which could produce multiple
5447 // callbacks and inadvertently unlinger networks.
5448 Arrays.sort(nais);
5449 for (NetworkAgentInfo nai : nais) {
5450 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005451 // Only reap the last time through the loop. Reaping before all rematching
5452 // is complete could incorrectly teardown a network that hasn't yet been
5453 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005454 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005455 : ReapUnvalidatedNetworks.REAP,
5456 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005457 }
5458 }
5459 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005460
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005461 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005462 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005463 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005464 // For now only update icons for default connection.
5465 // TODO: Update WiFi and cellular icons separately. b/17237507
5466 if (!isDefaultNetwork(nai)) return;
5467
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005468 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005469 // Don't repeat publish.
5470 if (newInetCondition == mDefaultInetConditionPublished) return;
5471
5472 mDefaultInetConditionPublished = newInetCondition;
5473 sendInetConditionBroadcast(nai.networkInfo);
5474 }
5475
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005476 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005477 synchronized (mVpns) {
5478 if (mLockdownTracker != null) {
5479 if (nai != null && nai.isVPN()) {
5480 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5481 } else {
5482 mLockdownTracker.onNetworkInfoChanged();
5483 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005484 }
5485 }
5486 }
5487
Robert Greenwalt7b816022014-04-18 15:25:25 -07005488 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005489 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005490 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005491 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005492 synchronized (networkAgent) {
5493 oldInfo = networkAgent.networkInfo;
5494 networkAgent.networkInfo = newInfo;
5495 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005496 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005497
Robert Greenwalt7b816022014-04-18 15:25:25 -07005498 if (DBG) {
5499 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5500 (oldInfo == null ? "null" : oldInfo.getState()) +
5501 " to " + state);
5502 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005503
Robin Lee585e2482016-05-01 23:00:00 +01005504 if (!networkAgent.created
5505 && (state == NetworkInfo.State.CONNECTED
5506 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005507
5508 // A network that has just connected has zero requests and is thus a foreground network.
5509 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5510
Robert Greenwalt7b816022014-04-18 15:25:25 -07005511 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005512 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005513 if (networkAgent.isVPN()) {
5514 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005515 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5516 (networkAgent.networkMisc == null ||
5517 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005518 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005519 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005520 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005521 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005522 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005523 loge("Error creating network " + networkAgent.network.netId + ": "
5524 + e.getMessage());
5525 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005526 }
Paul Jenseneec75412014-08-04 12:21:19 -04005527 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005528 }
5529
5530 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5531 networkAgent.everConnected = true;
5532
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005533 if (networkAgent.linkProperties == null) {
5534 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5535 }
5536
Erik Kline736353a2018-03-21 07:18:33 -07005537 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005538 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005539
Paul Jensenca8f16a2014-05-09 12:47:55 -04005540 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005541 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005542
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005543 if (networkAgent.isVPN()) {
5544 // Temporarily disable the default proxy (not global).
Chalard Jean52c2aa72018-06-07 16:44:04 +09005545 synchronized (mProxyTracker.mProxyLock) {
5546 if (!mProxyTracker.mDefaultProxyDisabled) {
5547 mProxyTracker.mDefaultProxyDisabled = true;
5548 if (mProxyTracker.mGlobalProxy == null
5549 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005550 mProxyTracker.sendProxyBroadcast(null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005551 }
5552 }
5553 }
5554 // TODO: support proxy per network.
5555 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005556
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005557 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5558 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5559 // capabilities, so it only needs to be done once on initial connect, not every time the
5560 // network's capabilities change. Note that we do this before rematching the network,
5561 // so we could decide to tear it down immediately afterwards. That's fine though - on
5562 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5563 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005564 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005565
Paul Jensen2161a8e2014-09-11 11:00:39 -04005566 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005567 final long now = SystemClock.elapsedRealtime();
5568 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005569
5570 // This has to happen after matching the requests, because callbacks are just requests.
5571 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005572 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005574 if (networkAgent.isVPN()) {
Chalard Jean52c2aa72018-06-07 16:44:04 +09005575 synchronized (mProxyTracker.mProxyLock) {
5576 if (mProxyTracker.mDefaultProxyDisabled) {
5577 mProxyTracker.mDefaultProxyDisabled = false;
5578 if (mProxyTracker.mGlobalProxy == null
5579 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005580 mProxyTracker.sendProxyBroadcast(mProxyTracker.mDefaultProxy);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005581 }
5582 }
5583 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005584 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005585 }
Chalard Jean392971c2018-05-11 20:19:20 +09005586 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005587 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5588 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005589 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005590 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005591 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005592 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005593 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5594 networkAgent.networkCapabilities);
5595 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5596 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005597 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5598 ConnectivityManager.CALLBACK_SUSPENDED :
5599 ConnectivityManager.CALLBACK_RESUMED));
5600 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005601 }
5602 }
5603
Robert Greenwaltac96c522014-06-03 16:43:57 -07005604 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005605 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005606 if (score < 0) {
5607 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5608 "). Bumping score to min of 0");
5609 score = 0;
5610 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005611
Paul Jensen2161a8e2014-09-11 11:00:39 -04005612 final int oldScore = nai.getCurrentScore();
5613 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005614
Paul Jensen85cf78e2015-06-25 13:25:07 -04005615 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005616
Paul Jensenc8b9a742014-09-30 15:37:41 -04005617 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005618 }
5619
Erik Klinec75d4fa2017-02-15 19:59:17 +09005620 // Notify only this one new request of the current state. Transfer all the
5621 // current state by calling NetworkCapabilities and LinkProperties callbacks
5622 // so that callers can be guaranteed to have as close to atomicity in state
5623 // transfer as can be supported by this current API.
5624 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005625 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005626 if (nri.mPendingIntent != null) {
5627 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5628 // Attempt no subsequent state pushes where intents are involved.
5629 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005630 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005631
5632 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005633 }
5634
Robert Greenwalt8d482522015-06-24 13:23:42 -07005635 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005636 // The NetworkInfo we actually send out has no bearing on the real
5637 // state of affairs. For example, if the default connection is mobile,
5638 // and a request for HIPRI has just gone away, we need to pretend that
5639 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5640 // the state to DISCONNECTED, even though the network is of type MOBILE
5641 // and is still connected.
5642 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5643 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005644 if (state != DetailedState.DISCONNECTED) {
5645 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005646 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005647 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005648 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005649 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5650 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5651 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5652 if (info.isFailover()) {
5653 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5654 nai.networkInfo.setFailover(false);
5655 }
5656 if (info.getReason() != null) {
5657 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5658 }
5659 if (info.getExtraInfo() != null) {
5660 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5661 }
5662 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005663 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005664 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005665 if (newDefaultAgent != null) {
5666 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5667 newDefaultAgent.networkInfo);
5668 } else {
5669 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5670 }
5671 }
5672 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5673 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005674 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005675 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005676 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005677 }
5678 }
5679 }
5680
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005681 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005682 if (VDBG) {
5683 String notification = ConnectivityManager.getCallbackName(notifyType);
5684 log("notifyType " + notification + " for " + networkAgent.name());
5685 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005686 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5687 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005688 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5689 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005690 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5691 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005692 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005693 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005694 } else {
5695 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5696 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005697 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005698 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005699
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005700 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5701 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5702 }
5703
Jeff Sharkey69736342014-12-08 14:50:12 -08005704 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005705 * Returns the list of all interfaces that could be used by network traffic that does not
5706 * explicitly specify a network. This includes the default network, but also all VPNs that are
5707 * currently connected.
5708 *
5709 * Must be called on the handler thread.
5710 */
5711 private Network[] getDefaultNetworks() {
5712 ArrayList<Network> defaultNetworks = new ArrayList<>();
5713 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5714 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5715 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5716 defaultNetworks.add(nai.network);
5717 }
5718 }
5719 return defaultNetworks.toArray(new Network[0]);
5720 }
5721
5722 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005723 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5724 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005725 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005726 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005727 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005728 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005729 } catch (Exception ignored) {
5730 }
5731 }
5732
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005733 @Override
5734 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005735 int user = UserHandle.getUserId(Binder.getCallingUid());
5736 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005737 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005738 return mVpns.get(user).addAddress(address, prefixLength);
5739 }
5740 }
5741
5742 @Override
5743 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005744 int user = UserHandle.getUserId(Binder.getCallingUid());
5745 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005746 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005747 return mVpns.get(user).removeAddress(address, prefixLength);
5748 }
5749 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005750
5751 @Override
5752 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005753 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005754 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005755 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005756 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005757 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005758 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005759 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005760 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005761 }
5762 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005763 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005764
5765 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005766 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005767 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005768 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005769 }
5770
5771 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005772 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5773 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5774 enforceKeepalivePermission();
5775 mKeepaliveTracker.startNattKeepalive(
5776 getNetworkAgentInfoForNetwork(network),
5777 intervalSeconds, messenger, binder,
5778 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5779 }
5780
5781 @Override
5782 public void stopKeepalive(Network network, int slot) {
5783 mHandler.sendMessage(mHandler.obtainMessage(
5784 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5785 }
5786
5787 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005788 public void factoryReset() {
5789 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005790
5791 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5792 return;
5793 }
5794
Robin Lee3b3dd942015-05-12 18:14:58 +01005795 final int userId = UserHandle.getCallingUserId();
5796
Stuart Scottf1fb3972015-04-02 18:00:02 -07005797 // Turn airplane mode off
5798 setAirplaneMode(false);
5799
Stuart Scotte3e314d2015-04-20 14:07:45 -07005800 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5801 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005802 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005803 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005804 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005805 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005806 }
5807
Stuart Scotte3e314d2015-04-20 14:07:45 -07005808 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005809 // Remove always-on package
5810 synchronized (mVpns) {
5811 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5812 if (alwaysOnPackage != null) {
5813 setAlwaysOnVpnPackage(userId, null, false);
5814 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5815 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005816
Hugo Benichi69744342017-11-27 10:57:16 +09005817 // Turn Always-on VPN off
5818 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5819 final long ident = Binder.clearCallingIdentity();
5820 try {
5821 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5822 mLockdownEnabled = false;
5823 setLockdownTracker(null);
5824 } finally {
5825 Binder.restoreCallingIdentity(ident);
5826 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005827 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005828
Hugo Benichi69744342017-11-27 10:57:16 +09005829 // Turn VPN off
5830 VpnConfig vpnConfig = getVpnConfig(userId);
5831 if (vpnConfig != null) {
5832 if (vpnConfig.legacy) {
5833 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5834 } else {
5835 // Prevent this app (packagename = vpnConfig.user) from initiating
5836 // VPN connections in the future without user intervention.
5837 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005838
Hugo Benichi69744342017-11-27 10:57:16 +09005839 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5840 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005841 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005842 }
5843 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005844
5845 Settings.Global.putString(mContext.getContentResolver(),
5846 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005847 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005848
Ricky Wai44dcbde2018-01-23 04:09:45 +00005849 @Override
5850 public byte[] getNetworkWatchlistConfigHash() {
5851 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5852 if (nwm == null) {
5853 loge("Unable to get NetworkWatchlistManager");
5854 return null;
5855 }
5856 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5857 return nwm.getWatchlistConfigHash();
5858 }
5859
Paul Jensencf4c2c62015-07-01 14:16:32 -04005860 @VisibleForTesting
5861 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5862 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5863 return new NetworkMonitor(context, handler, nai, defaultRequest);
5864 }
Erik Kline48f12f22016-04-14 17:30:59 +09005865
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005866 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005867 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5868 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005869 }
5870
5871 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005872 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5873 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5874 }
5875
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005876 @VisibleForTesting
5877 public boolean hasService(String name) {
5878 return ServiceManager.checkService(name) != null;
5879 }
5880
Hugo Benichi64901e52017-10-19 14:42:40 +09005881 @VisibleForTesting
5882 protected IpConnectivityMetrics.Logger metricsLogger() {
5883 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5884 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005885 }
5886
5887 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005888 int[] transports = nai.networkCapabilities.getTransportTypes();
5889 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005890 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005891
5892 private static boolean toBool(int encodedBoolean) {
5893 return encodedBoolean != 0; // Only 0 means false.
5894 }
5895
5896 private static int encodeBool(boolean b) {
5897 return b ? 1 : 0;
5898 }
mswest46386886f2018-03-12 10:34:34 -07005899
5900 @Override
5901 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5902 FileDescriptor err, String[] args, ShellCallback callback,
5903 ResultReceiver resultReceiver) {
5904 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5905 }
5906
5907 private class ShellCmd extends ShellCommand {
5908
5909 @Override
5910 public int onCommand(String cmd) {
5911 if (cmd == null) {
5912 return handleDefaultCommands(cmd);
5913 }
5914 final PrintWriter pw = getOutPrintWriter();
5915 try {
5916 switch (cmd) {
5917 case "airplane-mode":
5918 final String action = getNextArg();
5919 if ("enable".equals(action)) {
5920 setAirplaneMode(true);
5921 return 0;
5922 } else if ("disable".equals(action)) {
5923 setAirplaneMode(false);
5924 return 0;
5925 } else if (action == null) {
5926 final ContentResolver cr = mContext.getContentResolver();
5927 final int enabled = Settings.Global.getInt(cr,
5928 Settings.Global.AIRPLANE_MODE_ON);
5929 pw.println(enabled == 0 ? "disabled" : "enabled");
5930 return 0;
5931 } else {
5932 onHelp();
5933 return -1;
5934 }
5935 default:
5936 return handleDefaultCommands(cmd);
5937 }
5938 } catch (Exception e) {
5939 pw.println(e);
5940 }
5941 return -1;
5942 }
5943
5944 @Override
5945 public void onHelp() {
5946 PrintWriter pw = getOutPrintWriter();
5947 pw.println("Connectivity service commands:");
5948 pw.println(" help");
5949 pw.println(" Print this help text.");
5950 pw.println(" airplane-mode [enable|disable]");
5951 pw.println(" Turn airplane mode on or off.");
5952 pw.println(" airplane-mode");
5953 pw.println(" Get airplane mode.");
5954 }
5955 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07005956
5957 /**
5958 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
5959 * for testing.
5960 */
5961 private Vpn enforceActiveVpnOrNetworkStackPermission() {
5962 if (checkNetworkStackPermission()) {
5963 return null;
5964 }
5965 final int uid = Binder.getCallingUid();
5966 final int user = UserHandle.getUserId(uid);
5967 synchronized (mVpns) {
5968 Vpn vpn = mVpns.get(user);
5969 try {
5970 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
5971 } catch (NullPointerException e) {
5972 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
5973 }
5974 }
5975 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
5976 + "permission");
5977 }
5978
5979 /**
5980 * @param connectionInfo the connection to resolve.
5981 * @return {@code uid} if the connection is found and the app has permission to observe it
5982 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
5983 * connection is not found.
5984 */
5985 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
5986 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
5987 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
5988 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
5989 }
5990
5991 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
5992 connectionInfo.local, connectionInfo.remote);
5993
5994 /* Filter out Uids not associated with the VPN. */
5995 if (vpn != null && !vpn.appliesToUid(uid)) {
5996 return INVALID_UID;
5997 }
5998
5999 return uid;
6000 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006001}