blob: 64ad912342ad9cc6224400a684709cb727c05803 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070038import static android.os.Process.INVALID_UID;
39import static android.system.OsConstants.IPPROTO_TCP;
40import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060041
Hugo Benichia0385682017-03-22 17:07:57 +090042import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060043
Wenchao Tongf5ea3402015-03-04 13:26:38 -080044import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080045import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090046import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070047import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.ContentResolver;
50import android.content.Context;
51import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070052import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070053import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070054import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070055import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090057import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050059import android.net.IIpConnectivityMetrics;
60import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070061import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.INetworkPolicyListener;
63import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070064import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080065import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070066import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010067import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070068import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070069import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070071import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070073import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070074import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090075import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070076import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070077import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070078import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070079import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070080import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000081import android.net.NetworkWatchlistManager;
Jason Monk207900c2014-04-25 15:00:09 -040082import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070083import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040084import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040085import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060086import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090087import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090088import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070089import android.net.netlink.InetDiagMessage;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090090import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080092import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070093import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040094import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070096import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070098import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Looper;
100import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700101import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700102import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900103import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700104import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700105import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800107import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900108import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900109import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700110import android.os.ShellCallback;
111import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900112import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700113import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400114import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700116import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700117import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900120import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700121import android.util.LocalLog;
122import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600123import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800124import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700125import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500126import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
Wink Savilleab9321d2013-06-29 21:10:57 -0700130import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400131import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400132import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700133import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700134import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700135import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800136import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700137import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900138import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700139import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600140import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700141import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900142import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900143import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700144import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700145import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400146import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900147import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900148import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500149import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900150import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900151import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100152import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700153import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900154import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700155import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600156import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400157import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900158import com.android.server.connectivity.NetworkNotificationManager;
159import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700160import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900161import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800162import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700163import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100164import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500165import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700166import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700167import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900168import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700169import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700171import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700172
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700173import org.xmlpull.v1.XmlPullParser;
174import org.xmlpull.v1.XmlPullParserException;
175
176import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700178import java.io.FileNotFoundException;
179import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700180import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700182import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700183import java.net.InetAddress;
184import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700185import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700186import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700187import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700188import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900189import java.util.Comparator;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700190import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700191import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700192import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700193import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700194import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900195import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600196import java.util.SortedSet;
197import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
199/**
200 * @hide
201 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800202public class ConnectivityService extends IConnectivityManager.Stub
203 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900204 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Chalard Jean4133a122018-06-04 13:33:12 +0900206 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900207 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900208 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900209 private static final String NETWORK_ARG = "networks";
210 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900211
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900212 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700213 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900215 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700216
Jeff Sharkey899223b2012-08-04 15:24:58 -0700217 // TODO: create better separation between radio types and network types
218
Robert Greenwalt42acef32009-08-12 16:08:25 -0700219 // how long to wait before switching back to a radio's default network
220 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
221 // system property that can override the above value
222 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
223 "android.telephony.apn-restore";
224
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900225 // How long to wait before putting up a "This network doesn't have an Internet connection,
226 // connect anyway?" dialog after the user selects a network that doesn't validate.
227 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
228
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900229 // Default to 30s linger time-out. Modifiable only for testing.
230 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
231 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
232 @VisibleForTesting
233 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
234
Jeremy Joslin79294842014-12-03 17:15:28 -0800235 // How long to delay to removal of a pending intent based request.
236 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
237 private final int mReleasePendingIntentDelayMs;
238
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900239 private MockableSystemProperties mSystemProperties;
240
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800241 private Tethering mTethering;
242
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700243 private final PermissionMonitor mPermissionMonitor;
244
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700245 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700246
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900247 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700248 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900249 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700250
Hugo Benichi69744342017-11-27 10:57:16 +0900251 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
252 // a direct call to LockdownVpnTracker.isEnabled().
253 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700254 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900255 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700256 private LockdownVpnTracker mLockdownTracker;
257
Erik Klineda4bfa82015-04-30 12:58:40 +0900258 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700259 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700260 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700262 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800263 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700264 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900265 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700266
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700267 private String mCurrentTcpBufferSizes;
268
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900269 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900270 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
271 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900272
Paul Jensenb10e37f2014-11-25 12:33:08 -0500273 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400274 // Tear down networks that have no chance (e.g. even if validated) of becoming
275 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 // all networks have been rematched against all NetworkRequests.
277 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400278 // Don't reap networks. This should be passed when some networks have not yet been
279 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500280 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900281 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500282
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900283 private enum UnneededFor {
284 LINGER, // Determine whether this network is unneeded and should be lingered.
285 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
286 }
287
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700288 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700289 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700290 * from one net to another. Clear happens when we get a new
291 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
292 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700295
Robert Greenwalt434203a2010-10-11 16:00:27 -0700296 /**
297 * used internally to reload global proxy settings
298 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700299 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700300
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700301 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400302 * PAC manager has received new port.
303 */
304 private static final int EVENT_PROXY_HAS_CHANGED = 16;
305
Robert Greenwalte049c232014-04-11 15:53:27 -0700306 /**
307 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700308 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700309 */
310 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
311
Robert Greenwalt7b816022014-04-18 15:25:25 -0700312 /**
313 * used internally when registering NetworkAgents
314 * obj = Messenger
315 */
316 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
317
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 /**
319 * used to add a network request
320 * includes a NetworkRequestInfo
321 */
322 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
323
324 /**
325 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900326 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700327 * cancel it.
328 * includes a NetworkRequestInfo
329 */
330 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
331
332 /**
333 * used to add a network listener - no request
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
337
338 /**
339 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400340 * arg1 = UID of caller
341 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700342 */
343 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
344
Robert Greenwalta67be032014-05-16 15:49:14 -0700345 /**
346 * used internally when registering NetworkFactories
347 * obj = Messenger
348 */
349 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
350
Robert Greenwalt27711812014-06-25 16:45:57 -0700351 /**
352 * used internally to expire a wakelock when transitioning
353 * from one net to another. Expire happens when we fail to find
354 * a new network (typically after 1 minute) -
355 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
356 * a replacement network.
357 */
358 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
359
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700360 /**
361 * Used internally to indicate the system is ready.
362 */
363 private static final int EVENT_SYSTEM_READY = 25;
364
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800365 /**
366 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400367 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800368 */
369 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
370
371 /**
372 * used to remove a pending intent and its associated network request.
373 * arg1 = UID of caller
374 * obj = PendingIntent
375 */
376 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
377
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900378 /**
379 * used to specify whether a network should be used even if unvalidated.
380 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
381 * arg2 = whether to remember this choice in the future (1 or 0)
382 * obj = network
383 */
384 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
385
386 /**
387 * used to ask the user to confirm a connection to an unvalidated network.
388 * obj = network
389 */
390 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 /**
393 * used internally to (re)configure mobile data always-on settings.
394 */
395 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
396
Paul Jensen694f2b82015-06-17 14:15:39 -0400397 /**
398 * used to add a network listener with a pending intent
399 * obj = NetworkRequestInfo
400 */
401 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
402
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900403 /**
404 * used to specify whether a network should not be penalized when it becomes unvalidated.
405 */
406 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
407
408 /**
409 * used to trigger revalidation of a network.
410 */
411 private static final int EVENT_REVALIDATE_NETWORK = 36;
412
Erik Klinea24d4592018-01-11 21:07:29 +0900413 // Handle changes in Private DNS settings.
414 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
415
dalyk7301aa42018-03-05 12:42:22 -0500416 // Handle private DNS validation status updates.
417 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
418
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900419 private static String eventName(int what) {
420 return sMagicDecoderRing.get(what, Integer.toString(what));
421 }
422
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900423 /** Handler thread used for both of the handlers below. */
424 @VisibleForTesting
425 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700426 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700427 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700428 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700429 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900430 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700431
Mike Lockwood0f79b542009-08-14 14:18:49 -0400432 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800433 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400434
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700435 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700436 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800437 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700438
Chalard Jean52c2aa72018-06-07 16:44:04 +0900439 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
440 // the world when it changes.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900441 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400442
Erik Klineda4bfa82015-04-30 12:58:40 +0900443 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700444
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400445 private UserManager mUserManager;
446
Chalard Jean4133a122018-06-04 13:33:12 +0900447 private NetworkConfig[] mNetConfigs;
448 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700449
Robert Greenwalt50393202011-06-21 17:26:14 -0700450 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900451 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700452
Chalard Jean4133a122018-06-04 13:33:12 +0900453 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400454
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900455 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900456 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900457 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900458
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700459 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800460 private static final int MIN_NET_ID = 100; // some reserved marks
461 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700462 private int mNextNetId = MIN_NET_ID;
463
Robert Greenwalt34524f02014-05-18 16:22:10 -0700464 // sequence number of NetworkRequests
465 private int mNextNetworkRequestId = 1;
466
Erik Kline7523eb32015-07-09 18:24:03 +0900467 // NetworkRequest activity String log entries.
468 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
469 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
470
Hugo Benichic2ae2872016-07-11 11:05:12 +0900471 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900472 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900473 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
474
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900475 private static final int MAX_WAKELOCK_LOGS = 20;
476 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900477 private int mTotalWakelockAcquisitions = 0;
478 private int mTotalWakelockReleases = 0;
479 private long mTotalWakelockDurationMs = 0;
480 private long mMaxWakelockDurationMs = 0;
481 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900482
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
484 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400485 private static class ValidationLog {
486 final Network mNetwork;
Chalard Jeand771aa02018-04-26 16:16:10 +0900487 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489
Chalard Jeand771aa02018-04-26 16:16:10 +0900490 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 mNetwork = network;
Chalard Jeand771aa02018-04-26 16:16:10 +0900492 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400493 mLog = log;
494 }
495 }
Chalard Jean4133a122018-06-04 13:33:12 +0900496 private final ArrayDeque<ValidationLog> mValidationLogs = new ArrayDeque<>(MAX_VALIDATION_LOGS);
Paul Jensen0808eb82016-06-03 13:51:21 -0400497
Chalard Jeand771aa02018-04-26 16:16:10 +0900498 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900499 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700500 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
501 mValidationLogs.removeLast();
502 }
Chalard Jeand771aa02018-04-26 16:16:10 +0900503 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700504 }
505 }
506
Hugo Benichif9fdf872016-07-28 17:53:06 +0900507 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900508
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700509 @GuardedBy("mBandwidthRequests")
510 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
511
Erik Kline065ab6e2016-10-02 18:02:14 +0900512 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900513 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900514
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900515 @VisibleForTesting
516 final MultipathPolicyTracker mMultipathPolicyTracker;
517
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 /**
519 * Implements support for the legacy "one network per network type" model.
520 *
521 * We used to have a static array of NetworkStateTrackers, one for each
522 * network type, but that doesn't work any more now that we can have,
523 * for example, more that one wifi network. This class stores all the
524 * NetworkAgentInfo objects that support a given type, but the legacy
525 * API will only see the first one.
526 *
527 * It serves two main purposes:
528 *
529 * 1. Provide information about "the network for a given type" (since this
530 * API only supports one).
531 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
532 * the first network for a given type changes, or if the default network
533 * changes.
534 */
535 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900537 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900539
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540 /**
541 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
542 * Each list holds references to all NetworkAgentInfos that are used to
543 * satisfy requests for that network type.
544 *
545 * This array is built out at startup such that an unsupported network
546 * doesn't get an ArrayList instance, making this a tristate:
547 * unsupported, supported but not active and active.
548 *
549 * The actual lists are populated when we scan the network types that
550 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900551 *
552 * Threading model:
553 * - addSupportedType() is only called in the constructor
554 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
555 * They are therefore not thread-safe with respect to each other.
556 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
557 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
558 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561
562 public LegacyTypeTracker() {
563 mTypeLists = (ArrayList<NetworkAgentInfo>[])
564 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
565 }
566
567 public void addSupportedType(int type) {
568 if (mTypeLists[type] != null) {
569 throw new IllegalStateException(
570 "legacy list for type " + type + "already initialized");
571 }
Chalard Jean4133a122018-06-04 13:33:12 +0900572 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 }
574
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public boolean isTypeSupported(int type) {
576 return isNetworkTypeValid(type) && mTypeLists[type] != null;
577 }
578
579 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900580 synchronized (mTypeLists) {
581 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
582 return mTypeLists[type].get(0);
583 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
587
Robert Greenwalt8d482522015-06-24 13:23:42 -0700588 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900589 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 }
595 }
596
597 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 public void add(int type, NetworkAgentInfo nai) {
599 if (!isTypeSupported(type)) {
600 return; // Invalid network type.
601 }
602 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
603
604 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
605 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700606 return;
607 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 synchronized (mTypeLists) {
609 list.add(nai);
610 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900611
612 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
616 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 }
619
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
623 if (list == null || list.isEmpty()) {
624 return;
625 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627
Hugo Benichi78caa2582016-06-21 09:48:07 +0900628 synchronized (mTypeLists) {
629 if (!list.remove(nai)) {
630 return;
631 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 final DetailedState state = DetailedState.DISCONNECTED;
635
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 maybeLogBroadcast(nai, state, type, wasDefault);
638 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639 }
640
641 if (!list.isEmpty() && wasFirstNetwork) {
642 if (DBG) log("Other network available for type " + type +
643 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
646 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900647 }
648 }
649
650 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900651 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
652 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700653 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900654 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 }
656 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700657
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 // send out another legacy broadcast - currently only used for suspend/unsuspend
659 // toggle
660 public void update(NetworkAgentInfo nai) {
661 final boolean isDefault = isDefaultNetwork(nai);
662 final DetailedState state = nai.networkInfo.getDetailedState();
663 for (int type = 0; type < mTypeLists.length; type++) {
664 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700665 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900666 final boolean isFirst = contains && (nai == list.get(0));
667 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700668 maybeLogBroadcast(nai, state, type, isDefault);
669 sendLegacyNetworkBroadcast(nai, state, type);
670 }
671 }
672 }
673
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900675 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 String state = (nai.networkInfo != null) ?
677 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
678 "???/???";
679 return name + " " + state;
680 }
681
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 pw.println("mLegacyTypeTracker:");
684 pw.increaseIndent();
685 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900689 pw.println();
690 pw.println("Current state:");
691 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900692 synchronized (mTypeLists) {
693 for (int type = 0; type < mTypeLists.length; type++) {
694 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
695 for (NetworkAgentInfo nai : mTypeLists[type]) {
696 pw.println(type + " " + naiToString(nai));
697 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900698 }
699 }
700 pw.decreaseIndent();
701 pw.decreaseIndent();
702 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700703 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700704 }
705 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
706
Vishnu Nair5c010902017-10-26 10:08:50 -0700707 /**
708 * Helper class which parses out priority arguments and dumps sections according to their
709 * priority. If priority arguments are omitted, function calls the legacy dump command.
710 */
711 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
712 @Override
713 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
714 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
715 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
716 }
717
718 @Override
719 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
720 doDump(fd, pw, args, asProto);
721 }
722
723 @Override
724 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
725 doDump(fd, pw, args, asProto);
726 }
727 };
728
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700730 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900731 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
732 }
733
734 @VisibleForTesting
735 protected ConnectivityService(Context context, INetworkManagementService netManager,
736 INetworkStatsService statsService, INetworkPolicyManager policyManager,
737 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800738 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800739
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900740 mSystemProperties = getSystemProperties();
741
Hugo Benichif9fdf872016-07-28 17:53:06 +0900742 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900743 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900744 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900745 mNetworkRequests.put(mDefaultRequest, defaultNRI);
746 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900747
Chalard Jeandda156a2018-01-10 21:19:32 +0900748 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900749 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700750
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900751 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900752 mHandlerThread.start();
753 mHandler = new InternalHandler(mHandlerThread.getLooper());
754 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700755
Jeremy Joslin79294842014-12-03 17:15:28 -0800756 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
757 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
758
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900759 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900760
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700761 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700762 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800763 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700764 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900765 mPolicyManagerInternal = checkNotNull(
766 LocalServices.getService(NetworkPolicyManagerInternal.class),
767 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900768 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900769
Jeff Sharkey82f85212012-08-24 11:17:25 -0700770 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700771 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900774 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700775 } catch (RemoteException e) {
776 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700777 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700778 }
779
780 final PowerManager powerManager = (PowerManager) context.getSystemService(
781 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700782 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
783 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
784 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800785 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700786
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700787 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700788
Wink Saville51f456f2013-04-23 14:26:51 -0700789 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900790 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700791 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792 String[] naStrings = context.getResources().getStringArray(
793 com.android.internal.R.array.networkAttributes);
794 for (String naString : naStrings) {
795 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700796 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700797 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700798 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800799 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700800 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700801 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700802 }
Wink Saville51f456f2013-04-23 14:26:51 -0700803 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
804 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
805 n.type);
806 continue;
807 }
Wink Saville975c8482011-04-07 14:23:45 -0700808 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800809 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700810 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700811 continue;
812 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700813 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700814
Wink Saville975c8482011-04-07 14:23:45 -0700815 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700816 mNetworksDefined++;
817 } catch(Exception e) {
818 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700819 }
820 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700821
822 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
823 if (mNetConfigs[TYPE_VPN] == null) {
824 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
825 // don't need to add TYPE_VPN to mNetConfigs.
826 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
827 mNetworksDefined++; // used only in the log() statement below.
828 }
829
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900830 // Do the same for Ethernet, since it's often not specified in the configs, although many
831 // devices can use it via USB host adapters.
832 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
833 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
834 mNetworksDefined++;
835 }
836
Wink Saville5e56bc52013-07-29 15:00:57 -0700837 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700838
Robert Greenwalt50393202011-06-21 17:26:14 -0700839 mProtectedNetworks = new ArrayList<Integer>();
840 int[] protectedNetworks = context.getResources().getIntArray(
841 com.android.internal.R.array.config_protectedNetworks);
842 for (int p : protectedNetworks) {
843 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
844 mProtectedNetworks.add(p);
845 } else {
846 if (DBG) loge("Ignoring protectedNetwork " + p);
847 }
848 }
849
Erik Kline47222fc2017-04-30 19:36:15 +0900850 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800851
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700852 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
853
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700854 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700855 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100856 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700857 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700858 intentFilter.addAction(Intent.ACTION_USER_ADDED);
859 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000860 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700861 mContext.registerReceiverAsUser(
862 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000863 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
864 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900865
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700866 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700867 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700868 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700869 } catch (RemoteException e) {
870 loge("Error registering observer :" + e);
871 }
872
Erik Klineda4bfa82015-04-30 12:58:40 +0900873 mSettingsObserver = new SettingsObserver(mContext, mHandler);
874 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800875
Chalard Jean4133a122018-06-04 13:33:12 +0900876 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
877 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400878
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400879 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900880
881 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900882 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
883 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900884
885 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
886 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
887 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
888 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
889 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
890 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
891 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900892
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900893 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900894 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900895 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900896
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900897 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
898
Erik Kline1742fe12017-12-13 19:40:49 +0900899 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900900 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700902
Erik Kline47222fc2017-04-30 19:36:15 +0900903 private Tethering makeTethering() {
904 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900905 final TetheringDependencies deps = new TetheringDependencies() {
906 @Override
907 public boolean isTetheringSupported() {
908 return ConnectivityService.this.isTetheringSupported();
909 }
Erik Kline72302902018-06-14 17:36:40 +0900910 @Override
911 public NetworkRequest getDefaultNetworkRequest() {
912 return mDefaultRequest;
913 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900914 };
Erik Kline47222fc2017-04-30 19:36:15 +0900915 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
916 IoThread.get().getLooper(), new MockableSystemProperties(),
917 deps);
918 }
919
Chalard Jean26400492018-04-18 20:18:38 +0900920 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
921 final NetworkCapabilities netCap = new NetworkCapabilities();
922 netCap.addCapability(NET_CAPABILITY_INTERNET);
923 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
924 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
925 netCap.setSingleUid(uid);
926 return netCap;
927 }
928
Chalard Jeandda156a2018-01-10 21:19:32 +0900929 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900930 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900931 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900932 netCap.addCapability(NET_CAPABILITY_INTERNET);
933 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900934 if (transportType > -1) {
935 netCap.addTransportType(transportType);
936 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900937 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900938 }
939
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900940 // Used only for testing.
941 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700942 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900943 // changing ContentResolver to make registerContentObserver non-final).
944 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
945 // by subclassing SettingsObserver.
946 @VisibleForTesting
947 void updateMobileDataAlwaysOn() {
948 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
949 }
950
Erik Kline736353a2018-03-21 07:18:33 -0700951 // See FakeSettingsProvider comment above.
952 @VisibleForTesting
953 void updatePrivateDnsSettings() {
954 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
955 }
956
Erik Klineda4bfa82015-04-30 12:58:40 +0900957 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900958 final boolean enable = toBool(Settings.Global.getInt(
959 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900960 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
961 if (enable == isEnabled) {
962 return; // Nothing to do.
963 }
964
965 if (enable) {
966 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900967 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900968 } else {
969 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
970 }
971 }
972
973 private void registerSettingsCallbacks() {
974 // Watch for global HTTP proxy changes.
975 mSettingsObserver.observe(
976 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
977 EVENT_APPLY_GLOBAL_HTTP_PROXY);
978
979 // Watch for whether or not to keep mobile data always on.
980 mSettingsObserver.observe(
981 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
982 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
983 }
984
Erik Klinea24d4592018-01-11 21:07:29 +0900985 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700986 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
987 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900988 }
989 }
990
Robert Greenwalt34524f02014-05-18 16:22:10 -0700991 private synchronized int nextNetworkRequestId() {
992 return mNextNetworkRequestId++;
993 }
994
Paul Jensen67b0b072015-06-10 11:22:17 -0400995 @VisibleForTesting
996 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400997 synchronized (mNetworkForNetId) {
998 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
999 int netId = mNextNetId;
1000 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1001 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001002 if (!mNetIdInUse.get(netId)) {
1003 mNetIdInUse.put(netId, true);
1004 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001005 }
1006 }
1007 }
1008 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001009 }
1010
Chalard Jeanc0982912018-06-07 16:11:34 +09001011 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001013 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1014 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 state = nai.getNetworkState();
1017 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 final NetworkInfo info = new NetworkInfo(networkType, 0,
1020 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1022 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001023 final NetworkCapabilities capabilities = new NetworkCapabilities();
1024 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1025 !info.isRoaming());
1026 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001029 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 return state;
1031 } else {
1032 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001034 }
1035
junyulai4a192e22018-06-13 15:00:37 +08001036 @VisibleForTesting
1037 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 if (network == null) {
1039 return null;
1040 }
Erik Kline736353a2018-03-21 07:18:33 -07001041 return getNetworkAgentInfoForNetId(network.netId);
1042 }
1043
1044 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001045 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001046 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001050 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001051 synchronized (mVpns) {
1052 if (!mLockdownEnabled) {
1053 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001054 Vpn vpn = mVpns.get(user);
1055 if (vpn != null && vpn.appliesToUid(uid)) {
1056 return vpn.getUnderlyingNetworks();
1057 }
1058 }
1059 }
1060 return null;
1061 }
1062
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001064 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001065
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001066 final Network[] networks = getVpnUnderlyingNetworks(uid);
1067 if (networks != null) {
1068 // getUnderlyingNetworks() returns:
1069 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1070 // empty array => the VPN explicitly said "no default network".
1071 // non-empty array => the VPN specified one or more default networks; we use the
1072 // first one.
1073 if (networks.length > 0) {
1074 nai = getNetworkAgentInfoForNetwork(networks[0]);
1075 } else {
1076 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001077 }
1078 }
1079
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 return nai.getNetworkState();
1082 } else {
1083 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001085 }
1086
1087 /**
1088 * Check if UID should be blocked from using the network with the given LinkProperties.
1089 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1091 boolean ignoreBlocked) {
1092 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001093 if (ignoreBlocked) {
1094 return false;
1095 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001097 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1098 if (isSystem(uid)) {
1099 return false;
1100 }
Robin Lee17e61832016-05-09 13:46:28 +01001101 synchronized (mVpns) {
1102 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1103 if (vpn != null && vpn.isBlockingUid(uid)) {
1104 return true;
1105 }
1106 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001107 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001108 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 }
1110
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001111 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001112 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1113 return;
1114 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001115 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001116 synchronized (mBlockedAppUids) {
1117 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001118 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001119 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001120 blocked = false;
1121 } else {
1122 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001123 }
1124 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001125 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1126 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1127 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001128 }
1129
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001131 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1132 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001133 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1137
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001139 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 }
Hugo Benichi69744342017-11-27 10:57:16 +09001141 synchronized (mVpns) {
1142 if (mLockdownTracker != null) {
1143 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1144 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001145 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 }
1147
1148 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 * Return NetworkInfo for the active (i.e., connected) network interface.
1150 * It is assumed that at most one network is active at a time. If more
1151 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001152 * @return the info for the active network, or {@code null} if none is
1153 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 enforceAccessPermission();
1158 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001160 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1162 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164
Paul Jensen31a94f42015-02-13 14:18:39 -05001165 @Override
1166 public Network getActiveNetwork() {
1167 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001169 }
1170
1171 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001173 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001175 }
1176
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001178 final int user = UserHandle.getUserId(uid);
1179 int vpnNetId = NETID_UNSET;
1180 synchronized (mVpns) {
1181 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001182 // TODO : now that capabilities contain the UID, the appliesToUid test should
1183 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001184 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1185 }
1186 NetworkAgentInfo nai;
1187 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001188 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001189 if (nai != null) {
1190 final NetworkCapabilities requiredCaps =
1191 createDefaultNetworkCapabilitiesForUid(uid);
1192 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1193 return nai.network;
1194 }
1195 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 }
1197 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 if (nai != null
1199 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1200 nai = null;
1201 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001202 return nai != null ? nai.network : null;
1203 }
1204
Lorenzo Colitti18660282016-07-04 12:55:44 +09001205 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001206 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1207 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 final int uid = Binder.getCallingUid();
1209 NetworkState state = getUnfilteredActiveNetworkState(uid);
1210 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001211 }
1212
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001214 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001215 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001216 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001217 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001218 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001219 }
1220
1221 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 public NetworkInfo getNetworkInfo(int networkType) {
1223 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001224 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001225 if (getVpnUnderlyingNetworks(uid) != null) {
1226 // A VPN is active, so we may need to return one of its underlying networks. This
1227 // information is not available in LegacyTypeTracker, so we have to get it from
1228 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001229 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001230 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001231 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001232 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001233 }
1234 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001235 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001240 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001242 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001244 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001245 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001246 return state.networkInfo;
1247 } else {
1248 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001249 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001250 }
1251
1252 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 public NetworkInfo[] getAllNetworkInfo() {
1254 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001255 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001256 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1257 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 NetworkInfo info = getNetworkInfo(networkType);
1259 if (info != null) {
1260 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001263 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001266 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001267 public Network getNetworkForType(int networkType) {
1268 enforceAccessPermission();
1269 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001270 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001271 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001272 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001273 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001274 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001275 }
1276
1277 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 public Network[] getAllNetworks() {
1279 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001281 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001283 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001284 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001285 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001287 }
1288
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001289 @Override
1290 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1291 // The basic principle is: if an app's traffic could possibly go over a
1292 // network, without the app doing anything multinetwork-specific,
1293 // (hence, by "default"), then include that network's capabilities in
1294 // the array.
1295 //
1296 // In the normal case, app traffic only goes over the system's default
1297 // network connection, so that's the only network returned.
1298 //
1299 // With a VPN in force, some app traffic may go into the VPN, and thus
1300 // over whatever underlying networks the VPN specifies, while other app
1301 // traffic may go over the system default network (e.g.: a split-tunnel
1302 // VPN, or an app disallowed by the VPN), so the set of networks
1303 // returned includes the VPN's underlying networks and the system
1304 // default.
1305 enforceAccessPermission();
1306
Chalard Jean4133a122018-06-04 13:33:12 +09001307 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001308
1309 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001310 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001311 if (nc != null) {
1312 result.put(nai.network, nc);
1313 }
1314
Hugo Benichi69744342017-11-27 10:57:16 +09001315 synchronized (mVpns) {
1316 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001317 Vpn vpn = mVpns.get(userId);
1318 if (vpn != null) {
1319 Network[] networks = vpn.getUnderlyingNetworks();
1320 if (networks != null) {
1321 for (Network network : networks) {
1322 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001323 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001324 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001325 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001326 }
1327 }
1328 }
1329 }
1330 }
1331 }
1332
1333 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1334 out = result.values().toArray(out);
1335 return out;
1336 }
1337
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001339 public boolean isNetworkSupported(int networkType) {
1340 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001342 }
1343
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001344 /**
1345 * Return LinkProperties for the active (i.e., connected) default
1346 * network interface. It is assumed that at most one default network
1347 * is active at a time. If more than one is active, it is indeterminate
1348 * which will be returned.
1349 * @return the ip properties for the active network, or {@code null} if
1350 * none is active
1351 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001352 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001353 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 enforceAccessPermission();
1355 final int uid = Binder.getCallingUid();
1356 NetworkState state = getUnfilteredActiveNetworkState(uid);
1357 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001358 }
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001361 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001363 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1364 if (nai != null) {
1365 synchronized (nai) {
1366 return new LinkProperties(nai.linkProperties);
1367 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001368 }
1369 return null;
1370 }
1371
Robert Greenwalt12e67352014-05-13 21:41:06 -07001372 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001373 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001374 public LinkProperties getLinkProperties(Network network) {
1375 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001376 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1377 }
1378
1379 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1380 if (nai == null) {
1381 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001382 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001383 synchronized (nai) {
1384 return new LinkProperties(nai.linkProperties);
1385 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001386 }
1387
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001388 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001389 if (nai != null) {
1390 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001391 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001392 return networkCapabilitiesRestrictedForCallerPermissions(
1393 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001394 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001395 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001396 }
1397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001398 return null;
1399 }
1400
1401 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001402 public NetworkCapabilities getNetworkCapabilities(Network network) {
1403 enforceAccessPermission();
1404 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1405 }
1406
Chalard Jeanb03a6222018-04-11 21:09:10 +09001407 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001408 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001409 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001410 if (!checkSettingsPermission(callerPid, callerUid)) {
1411 newNc.setUids(null);
1412 newNc.setSSID(null);
1413 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001414 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001415 }
1416
Chalard Jeanb552c462018-02-21 18:43:54 +09001417 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1418 if (!checkSettingsPermission()) {
1419 nc.setSingleUid(Binder.getCallingUid());
1420 }
1421 }
1422
Chalard Jean26aa91a2018-03-20 19:13:57 +09001423 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1424 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1425 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1426 }
1427 }
1428
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001429 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001430 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001431 // Require internal since we're handing out IMSI details
1432 enforceConnectivityInternalPermission();
1433
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001434 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001435 for (Network network : getAllNetworks()) {
1436 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1437 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001438 // TODO (b/73321673) : NetworkState contains a copy of the
1439 // NetworkCapabilities, which may contain UIDs of apps to which the
1440 // network applies. Should the UIDs be cleared so as not to leak or
1441 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001442 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001443 }
1444 }
1445 return result.toArray(new NetworkState[result.size()]);
1446 }
1447
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001448 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001449 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001450 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001451 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1452 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1453 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001454 }
1455
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001456 @Override
1457 public boolean isActiveNetworkMetered() {
1458 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001459
Eric Enslenc81ef192018-02-07 18:03:53 -08001460 final int uid = Binder.getCallingUid();
1461 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001462 if (caps != null) {
1463 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1464 } else {
1465 // Always return the most conservative value
1466 return true;
1467 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001468 }
1469
Jeff Sharkey216c1812012-08-05 14:29:23 -07001470 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1471 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001472 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001473 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001474 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001475 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001476 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001477
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001478 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 * Ensure that a network route exists to deliver traffic to the specified
1480 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001481 * @param networkType the type of the network over which traffic to the
1482 * specified host is to be routed
1483 * @param hostAddress the IP address of the host to which the route is
1484 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 * @return {@code true} on success, {@code false} on failure
1486 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001487 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001488 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001490 if (mProtectedNetworks.contains(networkType)) {
1491 enforceConnectivityInternalPermission();
1492 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001493
Chad Brubakerc0234532014-02-14 13:24:29 -08001494 InetAddress addr;
1495 try {
1496 addr = InetAddress.getByAddress(hostAddress);
1497 } catch (UnknownHostException e) {
1498 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1499 return false;
1500 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001503 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 return false;
1505 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001506
1507 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1508 if (nai == null) {
1509 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1510 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1511 } else {
1512 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1513 }
1514 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001515 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001516
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001517 DetailedState netState;
1518 synchronized (nai) {
1519 netState = nai.networkInfo.getDetailedState();
1520 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001521
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001522 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001523 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001524 log("requestRouteToHostAddress on down network "
1525 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001526 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001527 }
1528 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001530
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001531 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001532 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001533 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001534 LinkProperties lp;
1535 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001536 synchronized (nai) {
1537 lp = nai.linkProperties;
1538 netId = nai.network.netId;
1539 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001540 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001541 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1542 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001543 } finally {
1544 Binder.restoreCallingIdentity(token);
1545 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001546 }
1547
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001548 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001549 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001550 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001551 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001552 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001553 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001554 if (bestRoute.getGateway().equals(addr)) {
1555 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001556 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001557 } else {
1558 // if we will connect to this through another route, add a direct route
1559 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001560 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001561 }
1562 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001563 if (DBG) log("Adding legacy route " + bestRoute +
1564 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001565 try {
1566 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1567 } catch (Exception e) {
1568 // never crash - catch them all
1569 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001570 return false;
1571 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001572 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
dalyk7301aa42018-03-05 12:42:22 -05001575 @VisibleForTesting
1576 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1577 @Override
1578 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1579 String hostname, boolean validated) {
1580 try {
1581 mHandler.sendMessage(mHandler.obtainMessage(
1582 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1583 new PrivateDnsValidationUpdate(netId,
1584 InetAddress.parseNumericAddress(ipAddress),
1585 hostname, validated)));
1586 } catch (IllegalArgumentException e) {
1587 loge("Error parsing ip address in validation event");
1588 }
1589 }
1590 };
1591
1592 @VisibleForTesting
1593 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001594 final IIpConnectivityMetrics ipConnectivityMetrics =
1595 IIpConnectivityMetrics.Stub.asInterface(
1596 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1597 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001598 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001599 return;
dalyk7301aa42018-03-05 12:42:22 -05001600 }
1601
1602 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001603 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001604 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1605 mNetdEventCallback);
1606 } catch (Exception e) {
1607 loge("Error registering netd callback: " + e);
1608 }
1609 }
1610
Jeff Sharkey75d31892018-01-18 22:01:59 +09001611 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001612 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001613 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001614 // TODO: notify UID when it has requested targeted updates
1615 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001616 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001617 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001618 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001619 if (restrictBackground) {
1620 log("onRestrictBackgroundChanged(true): disabling tethering");
1621 mTethering.untetherAll();
1622 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001623 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001624 };
1625
Robin Lee3b3dd942015-05-12 18:14:58 +01001626 /**
1627 * Require that the caller is either in the same user or has appropriate permission to interact
1628 * across users.
1629 *
1630 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1631 */
1632 private void enforceCrossUserPermission(int userId) {
1633 if (userId == UserHandle.getCallingUserId()) {
1634 // Not a cross-user call.
1635 return;
1636 }
1637 mContext.enforceCallingOrSelfPermission(
1638 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1639 "ConnectivityService");
1640 }
1641
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001642 private void enforceInternetPermission() {
1643 mContext.enforceCallingOrSelfPermission(
1644 android.Manifest.permission.INTERNET,
1645 "ConnectivityService");
1646 }
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001649 mContext.enforceCallingOrSelfPermission(
1650 android.Manifest.permission.ACCESS_NETWORK_STATE,
1651 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653
1654 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001655 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
Charles He36738632017-05-15 17:07:18 +01001658 private void enforceSettingsPermission() {
1659 mContext.enforceCallingOrSelfPermission(
1660 android.Manifest.permission.NETWORK_SETTINGS,
1661 "ConnectivityService");
1662 }
1663
Chalard Jeanb552c462018-02-21 18:43:54 +09001664 private boolean checkSettingsPermission() {
1665 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1666 android.Manifest.permission.NETWORK_SETTINGS);
1667 }
1668
1669 private boolean checkSettingsPermission(int pid, int uid) {
1670 return PERMISSION_GRANTED == mContext.checkPermission(
1671 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1672 }
1673
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001674 private void enforceTetherAccessPermission() {
1675 mContext.enforceCallingOrSelfPermission(
1676 android.Manifest.permission.ACCESS_NETWORK_STATE,
1677 "ConnectivityService");
1678 }
1679
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001680 private void enforceConnectivityInternalPermission() {
1681 mContext.enforceCallingOrSelfPermission(
1682 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1683 "ConnectivityService");
1684 }
1685
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001686 private boolean checkNetworkStackPermission() {
1687 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1688 android.Manifest.permission.NETWORK_STACK);
1689 }
1690
Hugo Benichi514da602016-07-19 15:59:27 +09001691 private void enforceConnectivityRestrictedNetworksPermission() {
1692 try {
1693 mContext.enforceCallingOrSelfPermission(
1694 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1695 "ConnectivityService");
1696 return;
1697 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1698 enforceConnectivityInternalPermission();
1699 }
1700
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001701 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001702 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001703 }
1704
Lorenzo Colitti18660282016-07-04 12:55:44 +09001705 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001706 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001707 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001708 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001709 }
1710
1711 private void sendInetConditionBroadcast(NetworkInfo info) {
1712 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1713 }
1714
Wink Saville628b0852011-08-04 15:01:58 -07001715 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001716 synchronized (mVpns) {
1717 if (mLockdownTracker != null) {
1718 info = new NetworkInfo(info);
1719 mLockdownTracker.augmentNetworkInfo(info);
1720 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001721 }
1722
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001723 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001724 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001725 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (info.isFailover()) {
1727 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1728 info.setFailover(false);
1729 }
1730 if (info.getReason() != null) {
1731 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1732 }
1733 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001734 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1735 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001737 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001738 return intent;
1739 }
1740
1741 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1742 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1743 }
1744
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001745 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001746 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1747 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1748 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001749 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001750 final long ident = Binder.clearCallingIdentity();
1751 try {
1752 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1753 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001757 }
1758
Mike Lockwood0f79b542009-08-14 14:18:49 -04001759 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001760 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001761 if (!mSystemReady) {
1762 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001763 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001764 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001765 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001766 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001767 }
1768
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001769 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001770 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001771 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001772 final NetworkInfo ni = intent.getParcelableExtra(
1773 ConnectivityManager.EXTRA_NETWORK_INFO);
1774 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1775 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1776 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001777 } else {
1778 BroadcastOptions opts = BroadcastOptions.makeBasic();
1779 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1780 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001781 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001782 final IBatteryStats bs = BatteryStatsService.getService();
1783 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001784 bs.noteConnectivityChanged(intent.getIntExtra(
1785 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001786 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001787 } catch (RemoteException e) {
1788 }
Chad Brubakerac925012018-03-08 10:37:09 -08001789 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001790 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001791 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001792 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001793 } finally {
1794 Binder.restoreCallingIdentity(ident);
1795 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001796 }
1797 }
1798
1799 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001800 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001801 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001802
Hugo Benichi20035e02017-04-26 14:53:28 +09001803 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001804 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001805 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001806 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001807 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001808 }
1809 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001810 // load the global proxy at startup
1811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001812
Robin Lee244ce8e2016-01-05 18:03:46 +00001813 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1814 // for user to unlock device too.
1815 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001816
Erik Klineda4bfa82015-04-30 12:58:40 +09001817 // Configure whether mobile data is always on.
1818 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1819
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001821
1822 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001827 *
1828 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001829 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001830 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001831 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1832 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001833
1834 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001836
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 if (networkAgent.networkCapabilities.hasTransport(
1838 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001839 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1840 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001841 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001842 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001843 } else if (networkAgent.networkCapabilities.hasTransport(
1844 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001845 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1846 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001847 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001848 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001849 } else {
1850 // do not track any other networks
1851 timeout = 0;
1852 }
1853
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001855 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001856 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001857 } catch (Exception e) {
1858 // You shall not crash!
1859 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001860 }
1861 }
1862 }
1863
1864 /**
1865 * Remove data activity tracking when network disconnects.
1866 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001867 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1868 final String iface = networkAgent.linkProperties.getInterfaceName();
1869 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001870
Robert Greenwalt7b816022014-04-18 15:25:25 -07001871 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1872 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001873 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001874 // the call fails silently if no idle timer setup for this interface
Haoyu Bai04124232012-06-28 15:26:19 -07001875 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001876 } catch (Exception e) {
1877 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001878 }
1879 }
1880 }
1881
1882 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08001883 * Update data activity tracking when network state is updated.
1884 */
1885 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
1886 NetworkAgentInfo oldNetwork) {
1887 if (newNetwork != null) {
1888 setupDataActivityTracking(newNetwork);
1889 }
1890 if (oldNetwork != null) {
1891 removeDataActivityTracking(oldNetwork);
1892 }
1893 }
1894 /**
Chalard Jean4d660112018-06-04 16:52:49 +09001895 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09001896 * and set it on it's iface.
1897 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001898 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1899 final String iface = newLp.getInterfaceName();
1900 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001901 if (oldLp == null && mtu == 0) {
1902 // Silently ignore unset MTU value.
1903 return;
1904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001905 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1906 if (VDBG) log("identical MTU - not setting");
1907 return;
1908 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001909 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001910 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001911 return;
1912 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001913
w1997615afd812014-08-05 15:18:11 -07001914 // Cannot set MTU without interface name
1915 if (TextUtils.isEmpty(iface)) {
1916 loge("Setting MTU size with null iface.");
1917 return;
1918 }
1919
Robert Greenwalt7b816022014-04-18 15:25:25 -07001920 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001921 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001922 mNetd.setMtu(iface, mtu);
1923 } catch (Exception e) {
1924 Slog.e(TAG, "exception in setMtu()" + e);
1925 }
1926 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001927
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001928 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001929 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1930
1931 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001932 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001933 protected MockableSystemProperties getSystemProperties() {
1934 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001935 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001936
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001937 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1938 if (isDefaultNetwork(nai) == false) {
1939 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001940 }
1941
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001942 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1943 String[] values = null;
1944 if (tcpBufferSizes != null) {
1945 values = tcpBufferSizes.split(",");
1946 }
1947
1948 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001949 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001950 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1951 values = tcpBufferSizes.split(",");
1952 }
1953
1954 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1955
1956 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001957 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001958
1959 final String prefix = "/sys/kernel/ipv4/tcp_";
1960 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1961 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1962 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1963 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1964 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1965 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1966 mCurrentTcpBufferSizes = tcpBufferSizes;
1967 } catch (IOException e) {
1968 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001969 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001970
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001971 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001972 Settings.Global.TCP_DEFAULT_INIT_RWND,
1973 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001974 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1975 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001976 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001977 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001978 }
1979
Robert Greenwalt562cc542014-05-15 18:07:26 -07001980 @Override
1981 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001982 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001983 NETWORK_RESTORE_DELAY_PROP_NAME);
1984 if(restoreDefaultNetworkDelayStr != null &&
1985 restoreDefaultNetworkDelayStr.length() != 0) {
1986 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001987 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001988 } catch (NumberFormatException e) {
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001991 // if the system property isn't set, use the value for the apn type
1992 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1993
1994 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1995 (mNetConfigs[networkType] != null)) {
1996 ret = mNetConfigs[networkType].restoreTime;
1997 }
1998 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002001 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2002 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2003 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002004 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002005 // Start gathering diagnostic information.
2006 netDiags.add(new NetworkDiagnostics(
2007 nai.network,
2008 new LinkProperties(nai.linkProperties), // Must be a copy.
2009 DIAG_TIME_MS));
2010 }
2011
2012 for (NetworkDiagnostics netDiag : netDiags) {
2013 pw.println();
2014 netDiag.waitForMeasurements();
2015 netDiag.dump(pw);
2016 }
2017 }
2018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002020 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002021 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2022 }
2023
2024 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002025 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002026 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002027 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002028
Erik Kline3f8306b2018-05-01 16:51:44 +09002029 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002030 dumpNetworkDiagnostics(pw);
2031 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002032 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002033 mTethering.dump(fd, pw, args);
2034 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002035 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2036 dumpNetworks(pw);
2037 return;
2038 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2039 dumpNetworkRequests(pw);
2040 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002041 }
Erik Kline379747a2015-06-05 17:47:34 +09002042
Lorenzo Colittie3805462015-06-03 11:18:24 +09002043 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002044 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002045 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002046 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002047 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002048 pw.println();
2049
Paul Jensen85cf78e2015-06-25 13:25:07 -04002050 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002051 pw.print("Active default network: ");
2052 if (defaultNai == null) {
2053 pw.println("none");
2054 } else {
2055 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002057 pw.println();
2058
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002059 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002060 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002061 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002063 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002064
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002065 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002066 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002067 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002068 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002069 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002070
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002071 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002072
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002073 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002074 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002075
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002076 pw.println();
2077 mKeepaliveTracker.dump(pw);
2078
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002079 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002080 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002081
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002082 pw.println();
2083 mMultipathPolicyTracker.dump(pw);
2084
Erik Kline3f8306b2018-05-01 16:51:44 +09002085 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002086 pw.println();
2087 synchronized (mValidationLogs) {
2088 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002089 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002090 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002091 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002092 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002093 pw.decreaseIndent();
2094 }
2095 }
Erik Kline7523eb32015-07-09 18:24:03 +09002096
2097 pw.println();
2098 pw.println("mNetworkRequestInfoLogs (most recent first):");
2099 pw.increaseIndent();
2100 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2101 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002102
2103 pw.println();
2104 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2105 pw.increaseIndent();
2106 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2107 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002108
2109 pw.println();
2110 pw.println("NetTransition WakeLock activity (most recent first):");
2111 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002112 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2113 pw.println("total releases: " + mTotalWakelockReleases);
2114 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2115 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2116 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2117 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2118 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2119 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002120 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002121
2122 pw.println();
2123 pw.println("bandwidth update requests (by uid):");
2124 pw.increaseIndent();
2125 synchronized (mBandwidthRequests) {
2126 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2127 pw.println("[" + mBandwidthRequests.keyAt(i)
2128 + "]: " + mBandwidthRequests.valueAt(i));
2129 }
2130 }
2131 pw.decreaseIndent();
2132
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002133 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136
Hugo Benichi14683812018-09-03 08:32:56 +09002137 private void dumpNetworks(IndentingPrintWriter pw) {
2138 for (NetworkAgentInfo nai : networksSortedById()) {
2139 pw.println(nai.toString());
2140 pw.increaseIndent();
2141 pw.println(String.format(
2142 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2143 nai.numForegroundNetworkRequests(),
2144 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2145 nai.numBackgroundNetworkRequests(),
2146 nai.numNetworkRequests()));
2147 pw.increaseIndent();
2148 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2149 pw.println(nai.requestAt(i).toString());
2150 }
2151 pw.decreaseIndent();
2152 pw.println("Lingered:");
2153 pw.increaseIndent();
2154 nai.dumpLingerTimers(pw);
2155 pw.decreaseIndent();
2156 pw.decreaseIndent();
2157 }
2158 }
2159
2160 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2161 for (NetworkRequestInfo nri : requestsSortedById()) {
2162 pw.println(nri.toString());
2163 }
2164 }
2165
Hugo Benichia2a917c2018-09-03 08:19:02 +09002166 /**
2167 * Return an array of all current NetworkAgentInfos sorted by network id.
2168 */
2169 private NetworkAgentInfo[] networksSortedById() {
2170 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2171 networks = mNetworkAgentInfos.values().toArray(networks);
2172 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2173 return networks;
2174 }
2175
2176 /**
2177 * Return an array of all current NetworkRequest sorted by request id.
2178 */
2179 private NetworkRequestInfo[] requestsSortedById() {
2180 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2181 requests = mNetworkRequests.values().toArray(requests);
2182 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2183 return requests;
2184 }
2185
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002186 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002187 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002188 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002189 if (officialNai != null && officialNai.equals(nai)) return true;
2190 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002191 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002192 " - " + nai);
2193 }
2194 return false;
2195 }
2196
Robert Greenwalt42acef32009-08-12 16:08:25 -07002197 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002198 private class NetworkStateTrackerHandler extends Handler {
2199 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002200 super(looper);
2201 }
2202
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002203 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002205 default:
2206 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002207 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002208 handleAsyncChannelHalfConnect(msg);
2209 break;
2210 }
2211 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2212 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2213 if (nai != null) nai.asyncChannel.disconnect();
2214 break;
2215 }
2216 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2217 handleAsyncChannelDisconnected(msg);
2218 break;
2219 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002220 }
2221 return true;
2222 }
2223
2224 private void maybeHandleNetworkAgentMessage(Message msg) {
2225 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2226 if (nai == null) {
2227 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002228 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002229 }
2230 return;
2231 }
2232
2233 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002234 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002235 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2236 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002237 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2238 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002239 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002240 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002241 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002242 break;
2243 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002244 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002245 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 break;
2247 }
2248 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002249 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002250 updateNetworkInfo(nai, info);
2251 break;
2252 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002253 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002254 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002255 break;
2256 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002257 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002258 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2259 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002260 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002261 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002262 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002263 break;
2264 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002265 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002266 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2267 break;
2268 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002269 }
2270 }
2271
2272 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2273 switch (msg.what) {
2274 default:
2275 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002276 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002277 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002278 if (nai == null) break;
2279
2280 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2281 final boolean wasValidated = nai.lastValidated;
2282 final boolean wasDefault = isDefaultNetwork(nai);
2283
Erik Klinea24d4592018-01-11 21:07:29 +09002284 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2285
Erik Klinea24d4592018-01-11 21:07:29 +09002286 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002287 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2288 ? " with redirect to " + redirectUrl
2289 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002290 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2291 }
Erik Klinea24d4592018-01-11 21:07:29 +09002292 if (valid != nai.lastValidated) {
2293 if (wasDefault) {
2294 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2295 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002296 }
Erik Klinea24d4592018-01-11 21:07:29 +09002297 final int oldScore = nai.getCurrentScore();
2298 nai.lastValidated = valid;
2299 nai.everValidated |= valid;
2300 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2301 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2302 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002303 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002304 }
2305 updateInetCondition(nai);
2306 // Let the NetworkAgent know the state of its network
2307 Bundle redirectUrlBundle = new Bundle();
2308 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2309 nai.asyncChannel.sendMessage(
2310 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2311 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2312 0, redirectUrlBundle);
2313 if (wasValidated && !nai.lastValidated) {
2314 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002315 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002316 break;
2317 }
Paul Jensen869868be2014-05-15 10:33:05 -04002318 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002319 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002320 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002321 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002322 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002323 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002324 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002325 nai.lastCaptivePortalDetected = visible;
2326 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002327 if (nai.lastCaptivePortalDetected &&
2328 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2329 if (DBG) log("Avoiding captive portal network: " + nai.name());
2330 nai.asyncChannel.sendMessage(
2331 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2332 teardownUnneededNetwork(nai);
2333 break;
2334 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002335 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002336 }
2337 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002338 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002339 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002340 if (nai == null) {
2341 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2342 break;
2343 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002344 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002345 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002346 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002347 }
Paul Jensen869868be2014-05-15 10:33:05 -04002348 }
Paul Jensen869868be2014-05-15 10:33:05 -04002349 break;
2350 }
Erik Klinea24d4592018-01-11 21:07:29 +09002351 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002352 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002353 if (nai == null) break;
2354
Erik Kline736353a2018-03-21 07:18:33 -07002355 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002356 break;
2357 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002358 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002359 return true;
2360 }
2361
Calvin Onbe96da12016-10-11 15:10:46 -07002362 private int getCaptivePortalMode() {
2363 return Settings.Global.getInt(mContext.getContentResolver(),
2364 Settings.Global.CAPTIVE_PORTAL_MODE,
2365 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2366 }
2367
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002368 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2369 switch (msg.what) {
2370 default:
2371 return false;
2372 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2373 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2374 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2375 handleLingerComplete(nai);
2376 }
2377 break;
2378 }
2379 }
2380 return true;
2381 }
2382
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002383 @Override
2384 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002385 if (!maybeHandleAsyncChannelMessage(msg) &&
2386 !maybeHandleNetworkMonitorMessage(msg) &&
2387 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002388 maybeHandleNetworkAgentMessage(msg);
2389 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002390 }
2391 }
2392
Erik Kline736353a2018-03-21 07:18:33 -07002393 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2394 return NetworkMonitor.isValidationRequired(
2395 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2396 }
2397
Erik Klinec6d00222018-06-26 18:53:43 +09002398 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2399 if (nai == null) return;
2400 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2401 // in order to restart a validation pass from within netd.
2402 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2403 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2404 updateDnses(nai.linkProperties, null, nai.network.netId);
2405 }
2406 }
2407
Erik Klinea24d4592018-01-11 21:07:29 +09002408 private void handlePrivateDnsSettingsChanged() {
2409 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2410
2411 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002412 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002413 if (networkRequiresValidation(nai)) {
2414 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2415 }
Erik Klinea24d4592018-01-11 21:07:29 +09002416 }
2417 }
2418
Erik Kline736353a2018-03-21 07:18:33 -07002419 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2420 // Private DNS only ever applies to networks that might provide
2421 // Internet access and therefore also require validation.
2422 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002423
Erik Kline736353a2018-03-21 07:18:33 -07002424 // Notify the NetworkMonitor thread in case it needs to cancel or
2425 // schedule DNS resolutions. If a DNS resolution is required the
2426 // result will be sent back to us.
2427 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2428
2429 // With Private DNS bypass support, we can proceed to update the
2430 // Private DNS config immediately, even if we're in strict mode
2431 // and have not yet resolved the provider name into a set of IPs.
2432 updatePrivateDns(nai, cfg);
2433 }
2434
2435 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2436 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002437 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002438 }
2439
dalyk7301aa42018-03-05 12:42:22 -05002440 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2441 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2442 if (nai == null) {
2443 return;
2444 }
2445 mDnsManager.updatePrivateDnsValidation(update);
2446 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2447 }
2448
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002449 private void updateLingerState(NetworkAgentInfo nai, long now) {
2450 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2451 // 2. If the network was lingering and there are now requests, unlinger it.
2452 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2453 // one lingered request, start lingering.
2454 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002455 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002456 if (DBG) log("Unlingering " + nai.name());
2457 nai.unlinger();
2458 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002459 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002460 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002461 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002462 nai.linger();
2463 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2464 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2465 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002466 }
2467
Robert Greenwalt7b816022014-04-18 15:25:25 -07002468 private void handleAsyncChannelHalfConnect(Message msg) {
2469 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002470 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002471 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2472 if (VDBG) log("NetworkFactory connected");
2473 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002474 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002475 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002476 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002477 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002478 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002479 }
2480 } else {
2481 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002482 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002483 }
2484 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2485 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2486 if (VDBG) log("NetworkAgent connected");
2487 // A network agent has requested a connection. Establish the connection.
2488 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2489 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2490 } else {
2491 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002492 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002494 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002495 synchronized (mNetworkForNetId) {
2496 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002497 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002498 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002499 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002500 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002502 }
2503 }
2504 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002505
Chalard Jean392971c2018-05-11 20:19:20 +09002506 // This is a no-op if it's called with a message designating a network that has
2507 // already been destroyed, because its reference will not be found in the relevant
2508 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002509 private void handleAsyncChannelDisconnected(Message msg) {
2510 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2511 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002512 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002513 } else {
2514 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2515 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002516 }
2517 }
2518
Chalard Jean392971c2018-05-11 20:19:20 +09002519 // Destroys a network, remove references to it from the internal state managed by
2520 // ConnectivityService, free its interfaces and clean up.
2521 // Must be called on the Handler thread.
2522 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2523 if (DBG) {
2524 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2525 }
2526 // A network agent has disconnected.
2527 // TODO - if we move the logic to the network agent (have them disconnect
2528 // because they lost all their requests or because their score isn't good)
2529 // then they would disconnect organically, report their new state and then
2530 // disconnect the channel.
2531 if (nai.networkInfo.isConnected()) {
2532 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2533 null, null);
2534 }
2535 final boolean wasDefault = isDefaultNetwork(nai);
2536 if (wasDefault) {
2537 mDefaultInetConditionPublished = 0;
2538 // Log default network disconnection before required book-keeping.
2539 // Let rematchAllNetworksAndRequests() below record a new default network event
2540 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2541 // whose timestamps tell how long it takes to recover a default network.
2542 long now = SystemClock.elapsedRealtime();
2543 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2544 }
2545 notifyIfacesChangedForNetworkStats();
2546 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2547 // by other networks that are already connected. Perhaps that can be done by
2548 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2549 // of rematchAllNetworksAndRequests
2550 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2551 mKeepaliveTracker.handleStopAllKeepalives(nai,
2552 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2553 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2554 // Disable wakeup packet monitoring for each interface.
2555 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2556 }
2557 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2558 mNetworkAgentInfos.remove(nai.messenger);
2559 nai.maybeStopClat();
2560 synchronized (mNetworkForNetId) {
2561 // Remove the NetworkAgent, but don't mark the netId as
2562 // available until we've told netd to delete it below.
2563 mNetworkForNetId.remove(nai.network.netId);
2564 }
2565 // Remove all previously satisfied requests.
2566 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2567 NetworkRequest request = nai.requestAt(i);
2568 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2569 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2570 clearNetworkForRequest(request.requestId);
2571 sendUpdatedScoreToFactories(request, 0);
2572 }
2573 }
2574 nai.clearLingerState();
2575 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002576 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002577 notifyLockdownVpn(nai);
2578 ensureNetworkTransitionWakelock(nai.name());
2579 }
2580 mLegacyTypeTracker.remove(nai, wasDefault);
2581 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2582 updateAllVpnsCapabilities();
2583 }
2584 rematchAllNetworksAndRequests(null, 0);
2585 mLingerMonitor.noteDisconnect(nai);
2586 if (nai.created) {
2587 // Tell netd to clean up the configuration for this network
2588 // (routing rules, DNS, etc).
2589 // This may be slow as it requires a lot of netd shelling out to ip and
2590 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2591 // after we've rematched networks with requests which should make a potential
2592 // fallback network the default or requested a new network from the
2593 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2594 // long time.
2595 try {
2596 mNetd.removeNetwork(nai.network.netId);
2597 } catch (Exception e) {
2598 loge("Exception removing network: " + e);
2599 }
2600 mDnsManager.removeNetwork(nai.network);
2601 }
2602 synchronized (mNetworkForNetId) {
2603 mNetIdInUse.delete(nai.network.netId);
2604 }
2605 }
2606
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002607 // If this method proves to be too slow then we can maintain a separate
2608 // pendingIntent => NetworkRequestInfo map.
2609 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2610 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2611 Intent intent = pendingIntent.getIntent();
2612 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2613 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2614 if (existingPendingIntent != null &&
2615 existingPendingIntent.getIntent().filterEquals(intent)) {
2616 return entry.getValue();
2617 }
2618 }
2619 return null;
2620 }
2621
2622 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2623 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2624
2625 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2626 if (existingRequest != null) { // remove the existing request.
2627 if (DBG) log("Replacing " + existingRequest.request + " with "
2628 + nri.request + " because their intents matched.");
2629 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2630 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002631 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002632 }
2633
Erik Klineda4bfa82015-04-30 12:58:40 +09002634 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002635 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002636 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002637 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002638 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002639 if (nri.request.networkCapabilities.hasSignalStrength() &&
2640 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2641 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002642 }
2643 }
2644 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002645 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002646 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002647 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002648 }
2649 }
2650
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002651 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2652 int callingUid) {
2653 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2654 if (nri != null) {
2655 handleReleaseNetworkRequest(nri.request, callingUid);
2656 }
2657 }
2658
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002659 // Determines whether the network is the best (or could become the best, if it validated), for
2660 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2661 // on the value of reason:
2662 //
2663 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2664 // then it should be torn down.
2665 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2666 // then it should be lingered.
2667 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2668 final int numRequests;
2669 switch (reason) {
2670 case TEARDOWN:
2671 numRequests = nai.numRequestNetworkRequests();
2672 break;
2673 case LINGER:
2674 numRequests = nai.numForegroundNetworkRequests();
2675 break;
2676 default:
2677 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2678 return true;
2679 }
2680
2681 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002682 return false;
2683 }
Paul Jensene0988542015-06-25 15:30:08 -04002684 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002685 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2686 // Background requests don't affect lingering.
2687 continue;
2688 }
2689
Paul Jensene0988542015-06-25 15:30:08 -04002690 // If this Network is already the highest scoring Network for a request, or if
2691 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002692 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002693 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002694 // Note that this catches two important cases:
2695 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2696 // is currently satisfying the request. This is desirable when
2697 // cellular ends up validating but WiFi does not.
2698 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002699 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002700 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002701 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002702 nai.getCurrentScoreAsValidated())) {
2703 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002704 }
2705 }
Paul Jensene0988542015-06-25 15:30:08 -04002706 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002707 }
2708
Erik Klineacdd6392016-07-07 16:50:58 +09002709 private NetworkRequestInfo getNriForAppRequest(
2710 NetworkRequest request, int callingUid, String requestedOperation) {
2711 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2712
Robert Greenwalt9258c642014-03-26 16:47:06 -07002713 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002714 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002715 log(String.format("UID %d attempted to %s for unowned request %s",
2716 callingUid, requestedOperation, nri));
2717 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002718 }
Erik Klineacdd6392016-07-07 16:50:58 +09002719 }
2720
2721 return nri;
2722 }
2723
Erik Kline57faba92015-11-25 12:49:38 +09002724 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002725 if (mNetworkRequests.get(nri.request) == null) {
2726 return;
Erik Kline57faba92015-11-25 12:49:38 +09002727 }
Hugo Benichicd952782017-09-20 11:20:14 +09002728 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002729 return;
2730 }
2731 if (VDBG || (DBG && nri.request.isRequest())) {
2732 log("releasing " + nri.request + " (timeout)");
2733 }
2734 handleRemoveNetworkRequest(nri);
2735 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002736 }
2737
Erik Klineacdd6392016-07-07 16:50:58 +09002738 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002739 final NetworkRequestInfo nri =
2740 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2741 if (nri == null) {
2742 return;
Erik Kline57faba92015-11-25 12:49:38 +09002743 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002744 if (VDBG || (DBG && nri.request.isRequest())) {
2745 log("releasing " + nri.request + " (release request)");
2746 }
2747 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002748 }
Erik Klineacdd6392016-07-07 16:50:58 +09002749
Hugo Benichidba33db2017-03-23 22:40:44 +09002750 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002751 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002752 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002753
Erik Klineacdd6392016-07-07 16:50:58 +09002754 synchronized (mUidToNetworkRequestCount) {
2755 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2756 if (requests < 1) {
2757 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2758 nri.mUid);
2759 } else if (requests == 1) {
2760 mUidToNetworkRequestCount.removeAt(
2761 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2762 } else {
2763 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2764 }
2765 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002766
Erik Klineacdd6392016-07-07 16:50:58 +09002767 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2768 if (nri.request.isRequest()) {
2769 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002770 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002771 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002772 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002773 nai.removeRequest(nri.request.requestId);
2774 if (VDBG) {
2775 log(" Removing from current network " + nai.name() +
2776 ", leaving " + nai.numNetworkRequests() + " requests.");
2777 }
2778 // If there are still lingered requests on this network, don't tear it down,
2779 // but resume lingering instead.
2780 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002781 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002782 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2783 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002784 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002785 wasKept = true;
2786 }
Hugo Benichicd952782017-09-20 11:20:14 +09002787 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002788 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2789 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002790 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002791 }
Erik Klineacdd6392016-07-07 16:50:58 +09002792 }
2793
2794 // TODO: remove this code once we know that the Slog.wtf is never hit.
2795 //
2796 // Find all networks that are satisfying this request and remove the request
2797 // from their request lists.
2798 // TODO - it's my understanding that for a request there is only a single
2799 // network satisfying it, so this loop is wasteful
2800 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2801 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2802 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2803 otherNai.name() + ", but mNetworkAgentInfos says " +
2804 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002805 }
2806 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002807
Erik Klineacdd6392016-07-07 16:50:58 +09002808 // Maintain the illusion. When this request arrived, we might have pretended
2809 // that a network connected to serve it, even though the network was already
2810 // connected. Now that this request has gone away, we might have to pretend
2811 // that the network disconnected. LegacyTypeTracker will generate that
2812 // phantom disconnect for this type.
2813 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2814 boolean doRemove = true;
2815 if (wasKept) {
2816 // check if any of the remaining requests for this network are for the
2817 // same legacy type - if so, don't remove the nai
2818 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2819 NetworkRequest otherRequest = nai.requestAt(i);
2820 if (otherRequest.legacyType == nri.request.legacyType &&
2821 otherRequest.isRequest()) {
2822 if (DBG) log(" still have other legacy request - leaving");
2823 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002824 }
2825 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002826 }
2827
Erik Klineacdd6392016-07-07 16:50:58 +09002828 if (doRemove) {
2829 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002830 }
2831 }
Erik Klineacdd6392016-07-07 16:50:58 +09002832
2833 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2834 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2835 nri.request);
2836 }
2837 } else {
2838 // listens don't have a singular affectedNetwork. Check all networks to see
2839 // if this listen request applies and remove it.
2840 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2841 nai.removeRequest(nri.request.requestId);
2842 if (nri.request.networkCapabilities.hasSignalStrength() &&
2843 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2844 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2845 }
2846 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002847 }
2848 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002849
Lorenzo Colitti18660282016-07-04 12:55:44 +09002850 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002851 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2852 enforceConnectivityInternalPermission();
2853 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002854 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002855 }
2856
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002857 @Override
2858 public void setAvoidUnvalidated(Network network) {
2859 enforceConnectivityInternalPermission();
2860 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2861 }
2862
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002863 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2864 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2865 " accept=" + accept + " always=" + always);
2866
2867 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2868 if (nai == null) {
2869 // Nothing to do.
2870 return;
2871 }
2872
2873 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002874 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002875 return;
2876 }
2877
2878 if (!nai.networkMisc.explicitlySelected) {
2879 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2880 }
2881
2882 if (accept != nai.networkMisc.acceptUnvalidated) {
2883 int oldScore = nai.getCurrentScore();
2884 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002885 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002886 sendUpdatedScoreToFactories(nai);
2887 }
2888
2889 if (always) {
2890 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002891 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002892 }
2893
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002894 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002895 // Tell the NetworkAgent to not automatically reconnect to the network.
2896 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09002897 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04002898 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002899 }
2900
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002901 }
2902
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002903 private void handleSetAvoidUnvalidated(Network network) {
2904 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2905 if (nai == null || nai.lastValidated) {
2906 // Nothing to do. The network either disconnected or revalidated.
2907 return;
2908 }
2909 if (!nai.avoidUnvalidated) {
2910 int oldScore = nai.getCurrentScore();
2911 nai.avoidUnvalidated = true;
2912 rematchAllNetworksAndRequests(nai, oldScore);
2913 sendUpdatedScoreToFactories(nai);
2914 }
2915 }
2916
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002917 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002918 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002919 mHandler.sendMessageDelayed(
2920 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2921 PROMPT_UNVALIDATED_DELAY_MS);
2922 }
2923
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002924 @Override
2925 public void startCaptivePortalApp(Network network) {
2926 enforceConnectivityInternalPermission();
2927 mHandler.post(() -> {
2928 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2929 if (nai == null) return;
2930 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2931 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2932 });
2933 }
2934
Hugo Benichic8e9e122016-09-14 23:23:08 +00002935 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002936 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002937 }
2938
Erik Kline065ab6e2016-10-02 18:02:14 +09002939 private void rematchForAvoidBadWifiUpdate() {
2940 rematchAllNetworksAndRequests(null, 0);
2941 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2942 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2943 sendUpdatedScoreToFactories(nai);
2944 }
2945 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002946 }
2947
Erik Kline065ab6e2016-10-02 18:02:14 +09002948 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002949 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002950 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002951 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002952 if (!configRestrict) {
2953 pw.println("Bad Wi-Fi avoidance: unrestricted");
2954 return;
2955 }
2956
2957 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2958 pw.increaseIndent();
2959 pw.println("Config restrict: " + configRestrict);
2960
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002961 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002962 String description;
2963 // Can't use a switch statement because strings are legal case labels, but null is not.
2964 if ("0".equals(value)) {
2965 description = "get stuck";
2966 } else if (value == null) {
2967 description = "prompt";
2968 } else if ("1".equals(value)) {
2969 description = "avoid";
2970 } else {
2971 description = value + " (?)";
2972 }
2973 pw.println("User setting: " + description);
2974 pw.println("Network overrides:");
2975 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09002976 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002977 if (nai.avoidUnvalidated) {
2978 pw.println(nai.name());
2979 }
2980 }
2981 pw.decreaseIndent();
2982 pw.decreaseIndent();
2983 }
2984
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002985 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2986 final String action;
2987 switch (type) {
2988 case NO_INTERNET:
2989 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2990 break;
2991 case LOST_INTERNET:
2992 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2993 break;
2994 default:
2995 Slog.wtf(TAG, "Unknown notification type " + type);
2996 return;
2997 }
2998
2999 Intent intent = new Intent(action);
3000 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3001 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3002 intent.setClassName("com.android.settings",
3003 "com.android.settings.wifi.WifiNoInternetDialog");
3004
3005 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3006 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3007 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3008 }
3009
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003010 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003011 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003012 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3013
3014 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3015 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003016 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003017 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003018 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3019 return;
3020 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003021 showValidationNotification(nai, NotificationType.NO_INTERNET);
3022 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003023
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003024 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3025 NetworkCapabilities nc = nai.networkCapabilities;
3026 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003027
Erik Kline065ab6e2016-10-02 18:02:14 +09003028 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003029 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003030 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3031 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003032 }
3033
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003034 @Override
3035 public int getMultipathPreference(Network network) {
3036 enforceAccessPermission();
3037
3038 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003039 if (nai != null && nai.networkCapabilities
3040 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003041 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3042 }
3043
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003044 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3045 if (networkPreference != null) {
3046 return networkPreference;
3047 }
3048
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003049 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3050 }
3051
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003052 private class InternalHandler extends Handler {
3053 public InternalHandler(Looper looper) {
3054 super(looper);
3055 }
3056
3057 @Override
3058 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003059 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003060 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003061 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003062 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003063 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003064 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003065 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003066 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003067 break;
3068 }
Jason Monkdecd2952013-10-10 14:02:51 -04003069 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003070 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003071 break;
3072 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003073 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003074 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3075 break;
3076 }
3077 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3078 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003079 break;
3080 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003081 case EVENT_REGISTER_NETWORK_AGENT: {
3082 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3083 break;
3084 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003085 case EVENT_REGISTER_NETWORK_REQUEST:
3086 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003087 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003088 break;
3089 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003090 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3091 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003092 handleRegisterNetworkRequestWithIntent(msg);
3093 break;
3094 }
Erik Kline57faba92015-11-25 12:49:38 +09003095 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3096 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3097 handleTimedOutNetworkRequest(nri);
3098 break;
3099 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003100 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3101 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3102 break;
3103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003104 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003105 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003106 break;
3107 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003108 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003109 Network network = (Network) msg.obj;
3110 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003111 break;
3112 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003113 case EVENT_SET_AVOID_UNVALIDATED: {
3114 handleSetAvoidUnvalidated((Network) msg.obj);
3115 break;
3116 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003117 case EVENT_PROMPT_UNVALIDATED: {
3118 handlePromptUnvalidated((Network) msg.obj);
3119 break;
3120 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003121 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3122 handleMobileDataAlwaysOn();
3123 break;
3124 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003125 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3126 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3127 mKeepaliveTracker.handleStartKeepalive(msg);
3128 break;
3129 }
3130 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3131 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3132 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3133 int slot = msg.arg1;
3134 int reason = msg.arg2;
3135 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3136 break;
3137 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003138 case EVENT_SYSTEM_READY: {
3139 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3140 nai.networkMonitor.systemReady = true;
3141 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003142 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003143 break;
3144 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003145 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003146 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003147 break;
3148 }
Erik Klinea24d4592018-01-11 21:07:29 +09003149 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3150 handlePrivateDnsSettingsChanged();
3151 break;
dalyk7301aa42018-03-05 12:42:22 -05003152 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3153 handlePrivateDnsValidationUpdate(
3154 (PrivateDnsValidationUpdate) msg.obj);
3155 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 }
3157 }
3158 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003159
3160 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003161 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003162 public int tether(String iface, String callerPkg) {
3163 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003164 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003165 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003166 } else {
3167 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3168 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003169 }
3170
3171 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003172 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003173 public int untether(String iface, String callerPkg) {
3174 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003175
3176 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003177 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003178 } else {
3179 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3180 }
3181 }
3182
3183 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003184 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003185 public int getLastTetherError(String iface) {
3186 enforceTetherAccessPermission();
3187
3188 if (isTetheringSupported()) {
3189 return mTethering.getLastTetherError(iface);
3190 } else {
3191 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3192 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003193 }
3194
3195 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003196 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003197 public String[] getTetherableUsbRegexs() {
3198 enforceTetherAccessPermission();
3199 if (isTetheringSupported()) {
3200 return mTethering.getTetherableUsbRegexs();
3201 } else {
3202 return new String[0];
3203 }
3204 }
3205
Lorenzo Colitti18660282016-07-04 12:55:44 +09003206 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003207 public String[] getTetherableWifiRegexs() {
3208 enforceTetherAccessPermission();
3209 if (isTetheringSupported()) {
3210 return mTethering.getTetherableWifiRegexs();
3211 } else {
3212 return new String[0];
3213 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003214 }
3215
Lorenzo Colitti18660282016-07-04 12:55:44 +09003216 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003217 public String[] getTetherableBluetoothRegexs() {
3218 enforceTetherAccessPermission();
3219 if (isTetheringSupported()) {
3220 return mTethering.getTetherableBluetoothRegexs();
3221 } else {
3222 return new String[0];
3223 }
3224 }
3225
Lorenzo Colitti18660282016-07-04 12:55:44 +09003226 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003227 public int setUsbTethering(boolean enable, String callerPkg) {
3228 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003229 if (isTetheringSupported()) {
3230 return mTethering.setUsbTethering(enable);
3231 } else {
3232 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3233 }
3234 }
3235
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003236 // TODO - move iface listing, queries, etc to new module
3237 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003238 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003239 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003240 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003241 return mTethering.getTetherableIfaces();
3242 }
3243
Lorenzo Colitti18660282016-07-04 12:55:44 +09003244 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003245 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003246 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003247 return mTethering.getTetheredIfaces();
3248 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003249
Lorenzo Colitti18660282016-07-04 12:55:44 +09003250 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003251 public String[] getTetheringErroredIfaces() {
3252 enforceTetherAccessPermission();
3253 return mTethering.getErroredIfaces();
3254 }
3255
Lorenzo Colitti18660282016-07-04 12:55:44 +09003256 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003257 public String[] getTetheredDhcpRanges() {
3258 enforceConnectivityInternalPermission();
3259 return mTethering.getTetheredDhcpRanges();
3260 }
3261
Udam Saini0e94c362017-06-07 12:06:28 -07003262 @Override
3263 public boolean isTetheringSupported(String callerPkg) {
3264 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3265 return isTetheringSupported();
3266 }
3267
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003268 // if ro.tether.denied = true we default to no tethering
3269 // gservices could set the secure setting to 1 though to enable it on a build where it
3270 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003271 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003272 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3273 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3274 Settings.Global.TETHER_SUPPORTED, defaultVal));
3275 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003276 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003277
3278 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3279 boolean adminUser = false;
3280 final long token = Binder.clearCallingIdentity();
3281 try {
3282 adminUser = mUserManager.isAdminUser();
3283 } finally {
3284 Binder.restoreCallingIdentity(token);
3285 }
3286
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003287 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003288 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003289
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003290 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003291 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3292 String callerPkg) {
3293 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003294 if (!isTetheringSupported()) {
3295 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3296 return;
3297 }
3298 mTethering.startTethering(type, receiver, showProvisioningUi);
3299 }
3300
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003301 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003302 public void stopTethering(int type, String callerPkg) {
3303 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003304 mTethering.stopTethering(type);
3305 }
3306
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003307 // Called when we lose the default network and have no replacement yet.
3308 // This will automatically be cleared after X seconds or a new default network
3309 // becomes CONNECTED, whichever happens first. The timer is started by the
3310 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003311 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003312 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003313 if (mNetTransitionWakeLock.isHeld()) {
3314 return;
3315 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003316 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003317 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3318 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003319 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003320 mWakelockLogs.log("ACQUIRE for " + forWhom);
3321 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3322 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003323 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003324
Hugo Benichi4c31b342017-03-30 23:18:10 +09003325 // Called when we gain a new default network to release the network transition wakelock in a
3326 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3327 // message is cancelled.
3328 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003329 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003330 if (!mNetTransitionWakeLock.isHeld()) {
3331 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003332 }
3333 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003334 // Cancel self timeout on wakelock hold.
3335 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3336 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3337 mHandler.sendMessageDelayed(msg, 1000);
3338 }
3339
3340 // Called when either message of ensureNetworkTransitionWakelock or
3341 // scheduleReleaseNetworkTransitionWakelock is processed.
3342 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3343 String event = eventName(eventId);
3344 synchronized (this) {
3345 if (!mNetTransitionWakeLock.isHeld()) {
3346 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3347 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3348 return;
3349 }
3350 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003351 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3352 mTotalWakelockDurationMs += lockDuration;
3353 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3354 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003355 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003356 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003357 }
3358
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003359 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003360 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003361 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003362 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003363 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003364 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003365 }
3366
Lorenzo Colitti18660282016-07-04 12:55:44 +09003367 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003368 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003369 enforceAccessPermission();
3370 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003371 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003372 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003373 mHandler.sendMessage(
3374 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3375 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003376
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003377 private void handleReportNetworkConnectivity(
3378 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003379 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003380 if (network == null) {
3381 nai = getDefaultNetwork();
3382 } else {
3383 nai = getNetworkAgentInfoForNetwork(network);
3384 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003385 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3386 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3387 return;
3388 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003389 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003390 if (hasConnectivity == nai.lastValidated) {
3391 return;
3392 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003393 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003394 int netid = nai.network.netId;
3395 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003396 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003397 // Validating a network that has not yet connected could result in a call to
3398 // rematchNetworkAndRequests() which is not meant to work on such networks.
3399 if (!nai.everConnected) {
3400 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003401 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003402 LinkProperties lp = getLinkProperties(nai);
3403 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3404 return;
3405 }
Erik Kline736353a2018-03-21 07:18:33 -07003406 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003407 }
3408
Lorenzo Colitti18660282016-07-04 12:55:44 +09003409 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003410 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003411 if (network == null) return mProxyTracker.getDefaultProxy();
3412 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003413 if (globalProxy != null) return globalProxy;
3414 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3415 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3416 // caller may not have.
3417 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3418 if (nai == null) return null;
3419 synchronized (nai) {
3420 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3421 if (proxyInfo == null) return null;
3422 return new ProxyInfo(proxyInfo);
3423 }
3424 }
3425
Chalard Jean3c443fc2018-06-07 18:37:59 +09003426 @Override
3427 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003428 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003429 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 }
3431
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003432 private void loadGlobalProxy() {
3433 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003434 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3435 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3436 String exclList = Settings.Global.getString(res,
3437 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003438 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3439 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003440 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003441 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003442 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003443 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003444 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003445 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003446 if (!proxyProperties.isValid()) {
3447 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3448 return;
3449 }
3450
Chalard Jean52c2aa72018-06-07 16:44:04 +09003451 synchronized (mProxyTracker.mProxyLock) {
3452 mProxyTracker.mGlobalProxy = proxyProperties;
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003453 }
3454 }
3455 }
3456
Chalard Jean5afbc832018-06-07 18:02:37 +09003457 @Override
3458 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003459 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003460 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003461 }
3462
Jason Monk207900c2014-04-25 15:00:09 -04003463 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003464 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003465 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003466 proxy = null;
3467 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003468 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 }
3470
Paul Jensene0bef712014-12-10 15:12:18 -05003471 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3472 // This method gets called when any network changes proxy, but the broadcast only ever contains
3473 // the default proxy (even if it hasn't changed).
3474 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3475 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003476 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003477 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3478 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3479
Chalard Jean4949dd72018-06-07 17:41:29 +09003480 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003481 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003482 }
3483 }
3484
Robert Greenwalt434203a2010-10-11 16:00:27 -07003485 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003486 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003487 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003488 if (!TextUtils.isEmpty(proxy)) {
3489 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003490 if (data.length == 0) {
3491 return;
3492 }
3493
Chalard Jean4133a122018-06-04 13:33:12 +09003494 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003495 int proxyPort = 8080;
3496 if (data.length > 1) {
3497 try {
3498 proxyPort = Integer.parseInt(data[1]);
3499 } catch (NumberFormatException e) {
3500 return;
3501 }
3502 }
Chalard Jean4133a122018-06-04 13:33:12 +09003503 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003504 setGlobalProxy(p);
3505 }
3506 }
3507
Robert Greenwalt434203a2010-10-11 16:00:27 -07003508 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003509 final private HashMap<Uri, Integer> mUriEventMap;
3510 final private Context mContext;
3511 final private Handler mHandler;
3512
3513 SettingsObserver(Context context, Handler handler) {
3514 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003515 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003516 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003517 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003518 }
3519
Erik Klineda4bfa82015-04-30 12:58:40 +09003520 void observe(Uri uri, int what) {
3521 mUriEventMap.put(uri, what);
3522 final ContentResolver resolver = mContext.getContentResolver();
3523 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003524 }
3525
3526 @Override
3527 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003528 Slog.wtf(TAG, "Should never be reached.");
3529 }
3530
3531 @Override
3532 public void onChange(boolean selfChange, Uri uri) {
3533 final Integer what = mUriEventMap.get(uri);
3534 if (what != null) {
3535 mHandler.obtainMessage(what.intValue()).sendToTarget();
3536 } else {
3537 loge("No matching event to send for URI=" + uri);
3538 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003539 }
3540 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003541
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003542 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003543 Slog.d(TAG, s);
3544 }
3545
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003546 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003547 Slog.e(TAG, s);
3548 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003549
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003550 private static void loge(String s, Throwable t) {
3551 Slog.e(TAG, s, t);
3552 }
3553
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003554 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003555 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003556 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3557 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3558 *
3559 * @param oldPackage Package name of the application which currently controls VPN, which will
3560 * be replaced. If there is no such application, this should should either be
3561 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3562 * @param newPackage Package name of the application which should gain control of VPN, or
3563 * {@code null} to disable.
3564 * @param userId User for whom to prepare the new VPN.
3565 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003566 * @hide
3567 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003568 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003569 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3570 int userId) {
3571 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003572
Hugo Benichi20035e02017-04-26 14:53:28 +09003573 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003574 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003575 Vpn vpn = mVpns.get(userId);
3576 if (vpn != null) {
3577 return vpn.prepare(oldPackage, newPackage);
3578 } else {
3579 return false;
3580 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003581 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003582 }
3583
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003584 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003585 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3586 * This method is used by system-privileged apps.
3587 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3588 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3589 *
3590 * @param packageName The package for which authorization state should change.
3591 * @param userId User for whom {@code packageName} is installed.
3592 * @param authorized {@code true} if this app should be able to start a VPN connection without
3593 * explicit user approval, {@code false} if not.
3594 *
Jeff Davidson05542602014-08-11 14:07:27 -07003595 * @hide
3596 */
3597 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003598 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3599 enforceCrossUserPermission(userId);
3600
Hugo Benichi20035e02017-04-26 14:53:28 +09003601 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003602 Vpn vpn = mVpns.get(userId);
3603 if (vpn != null) {
3604 vpn.setPackageAuthorization(packageName, authorized);
3605 }
Jeff Davidson05542602014-08-11 14:07:27 -07003606 }
3607 }
3608
3609 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003610 * Configure a TUN interface and return its file descriptor. Parameters
3611 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003612 * and not available in ConnectivityManager. Permissions are checked in
3613 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003614 * @hide
3615 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003616 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003617 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003618 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003619 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003620 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003621 return mVpns.get(user).establish(config);
3622 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003623 }
3624
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003625 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003626 * Start legacy VPN, controlling native daemons as needed. Creates a
3627 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003628 */
3629 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003630 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003631 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003632 final LinkProperties egress = getActiveLinkProperties();
3633 if (egress == null) {
3634 throw new IllegalStateException("Missing active network connection");
3635 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003636 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003637 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003638 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3639 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003640 }
3641
3642 /**
3643 * Return the information of the ongoing legacy VPN. This method is used
3644 * by VpnSettings and not available in ConnectivityManager. Permissions
3645 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003646 */
3647 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003648 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3649 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003650
Hugo Benichi20035e02017-04-26 14:53:28 +09003651 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003652 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003653 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003654 }
3655
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003656 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003657 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3658 * and not available in ConnectivityManager.
3659 */
3660 @Override
3661 public VpnInfo[] getAllVpnInfo() {
3662 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003663 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003664 if (mLockdownEnabled) {
3665 return new VpnInfo[0];
3666 }
3667
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003668 List<VpnInfo> infoList = new ArrayList<>();
3669 for (int i = 0; i < mVpns.size(); i++) {
3670 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3671 if (info != null) {
3672 infoList.add(info);
3673 }
3674 }
3675 return infoList.toArray(new VpnInfo[infoList.size()]);
3676 }
3677 }
3678
3679 /**
3680 * @return VPN information for accounting, or null if we can't retrieve all required
3681 * information, e.g primary underlying iface.
3682 */
3683 @Nullable
3684 private VpnInfo createVpnInfo(Vpn vpn) {
3685 VpnInfo info = vpn.getVpnInfo();
3686 if (info == null) {
3687 return null;
3688 }
3689 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3690 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3691 // the underlyingNetworks list.
3692 if (underlyingNetworks == null) {
3693 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3694 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3695 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3696 }
3697 } else if (underlyingNetworks.length > 0) {
3698 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3699 if (linkProperties != null) {
3700 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3701 }
3702 }
3703 return info.primaryUnderlyingIface == null ? null : info;
3704 }
3705
3706 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003707 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3708 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003709 * Permissions are checked in Vpn class.
3710 * @hide
3711 */
3712 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003713 public VpnConfig getVpnConfig(int userId) {
3714 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003715 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003716 Vpn vpn = mVpns.get(userId);
3717 if (vpn != null) {
3718 return vpn.getVpnConfig();
3719 } else {
3720 return null;
3721 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003722 }
3723 }
3724
Chalard Jean6b65ec72018-05-18 22:02:56 +09003725 /**
3726 * Ask all VPN objects to recompute and update their capabilities.
3727 *
3728 * When underlying networks change, VPNs may have to update capabilities to reflect things
3729 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3730 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3731 * handler thread through their agent, this is asynchronous. When the capabilities objects
3732 * are computed they will be up-to-date as they are computed synchronously from here and
3733 * this is running on the ConnectivityService thread.
3734 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3735 */
3736 private void updateAllVpnsCapabilities() {
3737 synchronized (mVpns) {
3738 for (int i = 0; i < mVpns.size(); i++) {
3739 final Vpn vpn = mVpns.valueAt(i);
3740 vpn.updateCapabilities();
3741 }
3742 }
3743 }
3744
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003745 @Override
3746 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003747 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3748 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3749 return false;
3750 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003751
Hugo Benichi69744342017-11-27 10:57:16 +09003752 synchronized (mVpns) {
3753 // Tear down existing lockdown if profile was removed
3754 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3755 if (mLockdownEnabled) {
3756 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3757 if (profileTag == null) {
3758 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3759 return false;
3760 }
3761 String profileName = new String(profileTag);
3762 final VpnProfile profile = VpnProfile.decode(
3763 profileName, mKeyStore.get(Credentials.VPN + profileName));
3764 if (profile == null) {
3765 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3766 setLockdownTracker(null);
3767 return true;
3768 }
3769 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003770 Vpn vpn = mVpns.get(user);
3771 if (vpn == null) {
3772 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3773 return false;
3774 }
3775 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003776 } else {
3777 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003778 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003779 }
3780
3781 return true;
3782 }
3783
3784 /**
3785 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3786 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3787 */
Hugo Benichi69744342017-11-27 10:57:16 +09003788 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003789 private void setLockdownTracker(LockdownVpnTracker tracker) {
3790 // Shutdown any existing tracker
3791 final LockdownVpnTracker existing = mLockdownTracker;
3792 mLockdownTracker = null;
3793 if (existing != null) {
3794 existing.shutdown();
3795 }
3796
Robin Leec3736bc2017-03-10 16:19:54 +00003797 if (tracker != null) {
3798 mLockdownTracker = tracker;
3799 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003800 }
3801 }
3802
Hugo Benichi69744342017-11-27 10:57:16 +09003803 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003804 private void throwIfLockdownEnabled() {
3805 if (mLockdownEnabled) {
3806 throw new IllegalStateException("Unavailable in lockdown mode");
3807 }
3808 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003809
Robin Lee244ce8e2016-01-05 18:03:46 +00003810 /**
Robin Lee17e61832016-05-09 13:46:28 +01003811 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3812 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003813 *
Robin Lee17e61832016-05-09 13:46:28 +01003814 * @return {@code true} if the service was started, the service was already connected, or there
3815 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003816 */
Robin Lee17e61832016-05-09 13:46:28 +01003817 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003818 synchronized (mVpns) {
3819 Vpn vpn = mVpns.get(userId);
3820 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003821 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003822 // exists already.
3823 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3824 return false;
3825 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003826
Robin Lee812800c2016-05-13 15:38:08 +01003827 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003828 }
3829 }
3830
3831 @Override
Charles He36738632017-05-15 17:07:18 +01003832 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3833 enforceSettingsPermission();
3834 enforceCrossUserPermission(userId);
3835
3836 synchronized (mVpns) {
3837 Vpn vpn = mVpns.get(userId);
3838 if (vpn == null) {
3839 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3840 return false;
3841 }
3842 return vpn.isAlwaysOnPackageSupported(packageName);
3843 }
3844 }
3845
3846 @Override
Robin Leedc679712016-05-03 13:23:03 +01003847 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003848 enforceConnectivityInternalPermission();
3849 enforceCrossUserPermission(userId);
3850
Robin Lee244ce8e2016-01-05 18:03:46 +00003851 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003852 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3853 if (LockdownVpnTracker.isEnabled()) {
3854 return false;
3855 }
3856
Robin Lee244ce8e2016-01-05 18:03:46 +00003857 Vpn vpn = mVpns.get(userId);
3858 if (vpn == null) {
3859 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3860 return false;
3861 }
Robin Lee17e61832016-05-09 13:46:28 +01003862 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003863 return false;
3864 }
Robin Lee17e61832016-05-09 13:46:28 +01003865 if (!startAlwaysOnVpn(userId)) {
3866 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003867 return false;
3868 }
3869 }
3870 return true;
3871 }
3872
3873 @Override
3874 public String getAlwaysOnVpnPackage(int userId) {
3875 enforceConnectivityInternalPermission();
3876 enforceCrossUserPermission(userId);
3877
3878 synchronized (mVpns) {
3879 Vpn vpn = mVpns.get(userId);
3880 if (vpn == null) {
3881 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3882 return null;
3883 }
3884 return vpn.getAlwaysOnPackage();
3885 }
3886 }
3887
Wink Savilleab9321d2013-06-29 21:10:57 -07003888 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003889 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003890 // TODO: Remove? Any reason to trigger a provisioning check?
3891 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003892 }
3893
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003894 /** Location to an updatable file listing carrier provisioning urls.
3895 * An example:
3896 *
3897 * <?xml version="1.0" encoding="utf-8"?>
3898 * <provisioningUrls>
3899 * <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 -07003900 * </provisioningUrls>
3901 */
3902 private static final String PROVISIONING_URL_PATH =
3903 "/data/misc/radio/provisioning_urls.xml";
3904 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003905
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003906 /** XML tag for root element. */
3907 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3908 /** XML tag for individual url */
3909 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003910 /** XML attribute for mcc */
3911 private static final String ATTR_MCC = "mcc";
3912 /** XML attribute for mnc */
3913 private static final String ATTR_MNC = "mnc";
3914
Paul Jensen434dde82015-06-11 09:43:30 -04003915 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003916 FileReader fileReader = null;
3917 XmlPullParser parser = null;
3918 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003919
3920 try {
3921 fileReader = new FileReader(mProvisioningUrlFile);
3922 parser = Xml.newPullParser();
3923 parser.setInput(fileReader);
3924 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3925
3926 while (true) {
3927 XmlUtils.nextElement(parser);
3928
3929 String element = parser.getName();
3930 if (element == null) break;
3931
Paul Jensen434dde82015-06-11 09:43:30 -04003932 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003933 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3934 try {
3935 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3936 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3937 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3938 parser.next();
3939 if (parser.getEventType() == XmlPullParser.TEXT) {
3940 return parser.getText();
3941 }
3942 }
3943 }
3944 } catch (NumberFormatException e) {
3945 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3946 }
3947 }
3948 }
3949 return null;
3950 } catch (FileNotFoundException e) {
3951 loge("Carrier Provisioning Urls file not found");
3952 } catch (XmlPullParserException e) {
3953 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3954 } catch (IOException e) {
3955 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3956 } finally {
3957 if (fileReader != null) {
3958 try {
3959 fileReader.close();
3960 } catch (IOException e) {}
3961 }
3962 }
3963 return null;
3964 }
3965
Wink Saville42d4f082013-07-20 20:31:59 -07003966 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003967 public String getMobileProvisioningUrl() {
3968 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003969 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003970 if (TextUtils.isEmpty(url)) {
3971 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003972 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003973 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003974 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003975 }
Wink Saville8cf35602013-07-10 23:00:07 -07003976 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003977 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003978 String phoneNumber = mTelephonyManager.getLine1Number();
3979 if (TextUtils.isEmpty(phoneNumber)) {
3980 phoneNumber = "0000000000";
3981 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003982 url = String.format(url,
3983 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3984 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09003985 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003986 }
3987
Wink Savilleab9321d2013-06-29 21:10:57 -07003988 return url;
3989 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003990
Wink Saville948282b2013-08-29 08:55:16 -07003991 @Override
3992 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003993 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003994 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003995 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3996 return;
3997 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003998 final long ident = Binder.clearCallingIdentity();
3999 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004000 // Concatenate the range of types onto the range of NetIDs.
4001 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4002 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004003 } finally {
4004 Binder.restoreCallingIdentity(ident);
4005 }
Wink Saville948282b2013-08-29 08:55:16 -07004006 }
Wink Saville7788c612013-08-29 14:57:08 -07004007
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004008 @Override
4009 public void setAirplaneMode(boolean enable) {
4010 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004011 final long ident = Binder.clearCallingIdentity();
4012 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004013 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004014 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004015 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4016 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004017 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004018 } finally {
4019 Binder.restoreCallingIdentity(ident);
4020 }
4021 }
4022
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004023 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004024 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004025 Vpn userVpn = mVpns.get(userId);
4026 if (userVpn != null) {
4027 loge("Starting user already has a VPN");
4028 return;
4029 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004030 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004031 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004032 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4033 updateLockdownVpn();
4034 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004035 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004036 }
4037
4038 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004039 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004040 Vpn userVpn = mVpns.get(userId);
4041 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004042 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004043 return;
4044 }
Robin Lee17e61832016-05-09 13:46:28 +01004045 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004046 mVpns.delete(userId);
4047 }
4048 }
4049
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004050 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004051 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004052 final int vpnsSize = mVpns.size();
4053 for (int i = 0; i < vpnsSize; i++) {
4054 Vpn vpn = mVpns.valueAt(i);
4055 vpn.onUserAdded(userId);
4056 }
4057 }
4058 }
4059
4060 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004061 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004062 final int vpnsSize = mVpns.size();
4063 for (int i = 0; i < vpnsSize; i++) {
4064 Vpn vpn = mVpns.valueAt(i);
4065 vpn.onUserRemoved(userId);
4066 }
4067 }
4068 }
4069
Robin Lee89e7a692016-02-29 14:38:17 +00004070 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004071 synchronized (mVpns) {
4072 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4073 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4074 updateLockdownVpn();
4075 } else {
4076 startAlwaysOnVpn(userId);
4077 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004078 }
4079 }
4080
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004081 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4082 @Override
4083 public void onReceive(Context context, Intent intent) {
4084 final String action = intent.getAction();
4085 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4086 if (userId == UserHandle.USER_NULL) return;
4087
Robin Lee323f29d2016-05-04 16:38:06 +01004088 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004089 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004090 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004091 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004092 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4093 onUserAdded(userId);
4094 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4095 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004096 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4097 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004098 }
4099 }
4100 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004101
Robin Lee95204e02017-01-27 11:59:22 +00004102 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4103 @Override
4104 public void onReceive(Context context, Intent intent) {
4105 // Try creating lockdown tracker, since user present usually means
4106 // unlocked keystore.
4107 updateLockdownVpn();
4108 mContext.unregisterReceiver(this);
4109 }
4110 };
4111
Chalard Jean4133a122018-06-04 13:33:12 +09004112 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4113 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004114
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004115 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4116 // Map from UID to number of NetworkRequests that UID has filed.
4117 @GuardedBy("mUidToNetworkRequestCount")
4118 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4119
Robert Greenwalta67be032014-05-16 15:49:14 -07004120 private static class NetworkFactoryInfo {
4121 public final String name;
4122 public final Messenger messenger;
4123 public final AsyncChannel asyncChannel;
4124
4125 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4126 this.name = name;
4127 this.messenger = messenger;
4128 this.asyncChannel = asyncChannel;
4129 }
4130 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004132 private void ensureNetworkRequestHasType(NetworkRequest request) {
4133 if (request.type == NetworkRequest.Type.NONE) {
4134 throw new IllegalArgumentException(
4135 "All NetworkRequests in ConnectivityService must have a type");
4136 }
4137 }
4138
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004139 /**
4140 * Tracks info about the requester.
4141 * Also used to notice when the calling process dies so we can self-expire
4142 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004145 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004146 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004147 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 final int mPid;
4149 final int mUid;
4150 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004152 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004153 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004154 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155 mPendingIntent = pi;
4156 messenger = null;
4157 mBinder = null;
4158 mPid = getCallingPid();
4159 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004160 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 }
4162
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004163 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 super();
4165 messenger = m;
4166 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004167 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 mBinder = binder;
4169 mPid = getCallingPid();
4170 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004172 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173
4174 try {
4175 mBinder.linkToDeath(this, 0);
4176 } catch (RemoteException e) {
4177 binderDied();
4178 }
4179 }
4180
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004181 private void enforceRequestCountLimit() {
4182 synchronized (mUidToNetworkRequestCount) {
4183 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4184 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004185 throw new ServiceSpecificException(
4186 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004187 }
4188 mUidToNetworkRequestCount.put(mUid, networkRequests);
4189 }
4190 }
4191
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 if (mBinder != null) {
4194 mBinder.unlinkToDeath(this, 0);
4195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196 }
4197
4198 public void binderDied() {
4199 log("ConnectivityService NetworkRequestInfo binderDied(" +
4200 request + ", " + mBinder + ")");
4201 releaseNetworkRequest(request);
4202 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004203
4204 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004205 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 }
4209
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004210 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4211 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4212 if (badCapability != null) {
4213 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004214 }
4215 }
4216
Chalard Jeanb03a6222018-04-11 21:09:10 +09004217 // This checks that the passed capabilities either do not request a specific SSID, or the
4218 // calling app has permission to do so.
4219 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4220 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004221 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004222 throw new SecurityException("Insufficient permissions to request a specific SSID");
4223 }
4224 }
4225
Erik Kline9d598e12015-07-13 16:37:51 +09004226 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004227 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004228 synchronized (nai) {
4229 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4230 if (nri.request.networkCapabilities.hasSignalStrength() &&
4231 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4232 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4233 }
4234 }
4235 }
Chalard Jean4133a122018-06-04 13:33:12 +09004236 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004237 }
4238
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004239 private void updateSignalStrengthThresholds(
4240 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4241 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004242 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004243 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4244
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004245 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004246 String detail;
4247 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4248 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4249 } else {
4250 detail = reason;
4251 }
4252 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4253 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4254 }
4255
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004256 nai.asyncChannel.sendMessage(
4257 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004258 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004259 }
4260
Etan Cohen859748f2017-04-03 17:42:34 -07004261 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4262 if (nc == null) {
4263 return;
4264 }
4265 NetworkSpecifier ns = nc.getNetworkSpecifier();
4266 if (ns == null) {
4267 return;
4268 }
4269 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4270 ns.assertValidFromUid(Binder.getCallingUid());
4271 }
4272
Robert Greenwalt9258c642014-03-26 16:47:06 -07004273 @Override
4274 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004275 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004276 final NetworkRequest.Type type = (networkCapabilities == null)
4277 ? NetworkRequest.Type.TRACK_DEFAULT
4278 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004279 // If the requested networkCapabilities is null, take them instead from
4280 // the default network request. This allows callers to keep track of
4281 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004282 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004283 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004284 enforceAccessPermission();
4285 } else {
4286 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4287 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004288 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4289 // of the app when the request is filed, but we never change the request if the app
4290 // changes network state. http://b/29964605
4291 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004292 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004293 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004294 ensureSufficientPermissionsForRequest(networkCapabilities,
4295 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004296 // Set the UID range for this request to the single UID of the requester, or to an empty
4297 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004298 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4299 // are no visible methods to set the UIDs, an app could use reflection to try and get
4300 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004301 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004302
Etan Cohenba07c8c2017-02-05 10:42:27 -08004303 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004304 throw new IllegalArgumentException("Bad timeout specified");
4305 }
Etan Cohen859748f2017-04-03 17:42:34 -07004306 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004307
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004308 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004309 nextNetworkRequestId(), type);
4310 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004311 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004312
4313 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004314 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004315 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004316 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004317 }
4318 return networkRequest;
4319 }
4320
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004321 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004322 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004323 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004324 } else {
4325 enforceChangePermission();
4326 }
4327 }
4328
fenglub15e72b2015-03-20 11:29:56 -07004329 @Override
fengludb571472015-04-21 17:12:05 -07004330 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004331 enforceAccessPermission();
4332 NetworkAgentInfo nai = null;
4333 if (network == null) {
4334 return false;
4335 }
4336 synchronized (mNetworkForNetId) {
4337 nai = mNetworkForNetId.get(network.netId);
4338 }
4339 if (nai != null) {
4340 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004341 synchronized (mBandwidthRequests) {
4342 final int uid = Binder.getCallingUid();
4343 Integer uidReqs = mBandwidthRequests.get(uid);
4344 if (uidReqs == null) {
4345 uidReqs = new Integer(0);
4346 }
4347 mBandwidthRequests.put(uid, ++uidReqs);
4348 }
fenglub15e72b2015-03-20 11:29:56 -07004349 return true;
4350 }
4351 return false;
4352 }
4353
Felipe Lemeee27cab2016-06-20 16:36:29 -07004354 private boolean isSystem(int uid) {
4355 return uid < Process.FIRST_APPLICATION_UID;
4356 }
fenglub15e72b2015-03-20 11:29:56 -07004357
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004358 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004359 final int uid = Binder.getCallingUid();
4360 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004361 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004362 return;
4363 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004364 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4365 // Policy already enforced.
4366 return;
4367 }
4368 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4369 // If UID is restricted, don't allow them to bring up metered APNs.
4370 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004371 }
4372 }
4373
Robert Greenwalt9258c642014-03-26 16:47:06 -07004374 @Override
4375 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4376 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004377 checkNotNull(operation, "PendingIntent cannot be null.");
4378 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4379 enforceNetworkRequestPermissions(networkCapabilities);
4380 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004381 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004382 ensureSufficientPermissionsForRequest(networkCapabilities,
4383 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004384 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004385 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004386
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004387 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004388 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4389 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004390 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004391 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4392 nri));
4393 return networkRequest;
4394 }
4395
Jeremy Joslin79294842014-12-03 17:15:28 -08004396 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4397 mHandler.sendMessageDelayed(
4398 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4399 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4400 }
4401
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004402 @Override
4403 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004404 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004405 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4406 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004407 }
4408
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004409 // In order to implement the compatibility measure for pre-M apps that call
4410 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4411 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4412 // This ensures it has permission to do so.
4413 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4414 if (nc == null) {
4415 return false;
4416 }
4417 int[] transportTypes = nc.getTransportTypes();
4418 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4419 return false;
4420 }
4421 try {
4422 mContext.enforceCallingOrSelfPermission(
4423 android.Manifest.permission.ACCESS_WIFI_STATE,
4424 "ConnectivityService");
4425 } catch (SecurityException e) {
4426 return false;
4427 }
4428 return true;
4429 }
4430
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 @Override
4432 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4433 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004434 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4435 enforceAccessPermission();
4436 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004437
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004438 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004439 ensureSufficientPermissionsForRequest(networkCapabilities,
4440 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004441 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004442 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4443 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4444 // onLost and onAvailable callbacks when networks move in and out of the background.
4445 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4446 // can't request networks.
4447 restrictBackgroundRequestForCaller(nc);
4448 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004449
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004450 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004451 NetworkRequest.Type.LISTEN);
4452 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004453 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004454
4455 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4456 return networkRequest;
4457 }
4458
4459 @Override
4460 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4461 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004462 checkNotNull(operation, "PendingIntent cannot be null.");
4463 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4464 enforceAccessPermission();
4465 }
Etan Cohen859748f2017-04-03 17:42:34 -07004466 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004467 ensureSufficientPermissionsForRequest(networkCapabilities,
4468 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004469
Chalard Jeandda156a2018-01-10 21:19:32 +09004470 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004471 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004472
4473 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004474 NetworkRequest.Type.LISTEN);
4475 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004476 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004477
4478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004479 }
4480
Erik Klineacdd6392016-07-07 16:50:58 +09004481 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004482 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004483 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004484 mHandler.sendMessage(mHandler.obtainMessage(
4485 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004486 }
4487
4488 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004489 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004490 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004491 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004493 }
4494
Robert Greenwalta67be032014-05-16 15:49:14 -07004495 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004496 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004497 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4498 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4499 }
4500
4501 @Override
4502 public void unregisterNetworkFactory(Messenger messenger) {
4503 enforceConnectivityInternalPermission();
4504 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4505 }
4506
4507 private void handleUnregisterNetworkFactory(Messenger messenger) {
4508 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4509 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004510 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004511 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004513 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004514 }
4515
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 /**
4517 * NetworkAgentInfo supporting a request by requestId.
4518 * These have already been vetted (their Capabilities satisfy the request)
4519 * and the are the highest scored network available.
4520 * the are keyed off the Requests requestId.
4521 */
Hugo Benichicd952782017-09-20 11:20:14 +09004522 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4523 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004524 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525
Paul Jensen31a94f42015-02-13 14:18:39 -05004526 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4527 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004528 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004529 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4530 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4531 // there may not be a strict 1:1 correlation between the two.
4532 @GuardedBy("mNetworkForNetId")
4533 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004534
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 // NetworkAgentInfo keyed off its connecting messenger
4536 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004537 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004538 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004540 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004541 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004542
Paul Jensen2c311d62014-11-17 12:34:51 -05004543 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004545
Erik Klineda4bfa82015-04-30 12:58:40 +09004546 // Request used to optionally keep mobile data active even when higher
4547 // priority networks like Wi-Fi are active.
4548 private final NetworkRequest mDefaultMobileDataRequest;
4549
Hugo Benichicd952782017-09-20 11:20:14 +09004550 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4551 synchronized (mNetworkForRequestId) {
4552 return mNetworkForRequestId.get(requestId);
4553 }
4554 }
4555
4556 private void clearNetworkForRequest(int requestId) {
4557 synchronized (mNetworkForRequestId) {
4558 mNetworkForRequestId.remove(requestId);
4559 }
4560 }
4561
4562 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4563 synchronized (mNetworkForRequestId) {
4564 mNetworkForRequestId.put(requestId, nai);
4565 }
4566 }
4567
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004568 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004569 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004570 }
4571
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004572 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004573 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004574 }
4575
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004576 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4577 return nri.request.requestId == mDefaultRequest.requestId;
4578 }
4579
Paul Jensen31a94f42015-02-13 14:18:39 -05004580 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004582 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004583 enforceConnectivityInternalPermission();
4584
Rubin Xu1bb5c082017-09-05 18:40:49 +01004585 LinkProperties lp = new LinkProperties(linkProperties);
4586 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004587 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4588 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004589 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004590 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004591 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004592 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004593 // Make sure the network capabilities reflect what the agent info says.
4594 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004595 synchronized (this) {
4596 nai.networkMonitor.systemReady = mSystemReady;
4597 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004598 final String extraInfo = networkInfo.getExtraInfo();
4599 final String name = TextUtils.isEmpty(extraInfo)
4600 ? nai.networkCapabilities.getSSID() : extraInfo;
4601 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004602 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004603 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004604 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004605 }
4606
Erik Klinee5dac902018-03-04 21:01:01 +09004607 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004609 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004610 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004611 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004612 }
Erik Klinee5dac902018-03-04 21:01:01 +09004613 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4614 NetworkInfo networkInfo = nai.networkInfo;
4615 nai.networkInfo = null;
4616 updateNetworkInfo(nai, networkInfo);
4617 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004618 }
4619
4620 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004621 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004622 int netId = networkAgent.network.netId;
4623
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004624 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4625 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004626 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004627 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004628 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004629
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004630 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004631 updateMtu(newLp, oldLp);
4632 // TODO - figure out what to do for clat
4633// for (LinkProperties lp : newLp.getStackedLinks()) {
4634// updateMtu(lp, null);
4635// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004636 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004637
Erik Kline94887872016-04-05 13:30:49 +09004638 updateRoutes(newLp, oldLp, netId);
4639 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004640 // Make sure LinkProperties represents the latest private DNS status.
4641 // This does not need to be done before updateDnses because the
4642 // LinkProperties are not the source of the private DNS configuration.
4643 // updateDnses will fetch the private DNS configuration from DnsManager.
4644 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004645
Hugo Benichi6f62b732017-06-27 15:13:20 +09004646 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004647 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004648 if (isDefaultNetwork(networkAgent)) {
4649 handleApplyDefaultProxy(newLp.getHttpProxy());
4650 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004651 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004652 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004653 // TODO - move this check to cover the whole function
4654 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004655 synchronized (networkAgent) {
4656 networkAgent.linkProperties = newLp;
4657 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004658 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004659 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4660 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004661
4662 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004663 }
4664
Joel Scherpelz668370b2017-06-08 15:35:21 +09004665 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004666 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004667 // marks on unsupported interfaces is harmless.
4668 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4669 return;
4670 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004671
Joel Scherpelz668370b2017-06-08 15:35:21 +09004672 int mark = mContext.getResources().getInteger(
4673 com.android.internal.R.integer.config_networkWakeupPacketMark);
4674 int mask = mContext.getResources().getInteger(
4675 com.android.internal.R.integer.config_networkWakeupPacketMask);
4676
4677 // Mask/mark of zero will not detect anything interesting.
4678 // Don't install rules unless both values are nonzero.
4679 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004680 return;
4681 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004682
4683 final String prefix = "iface:" + iface;
4684 try {
4685 if (add) {
4686 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4687 } else {
4688 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4689 }
4690 } catch (Exception e) {
4691 loge("Exception modifying wakeup packet monitoring: " + e);
4692 }
4693
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004694 }
4695
4696 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4697 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004698 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004699 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4700 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004701 for (String iface : interfaceDiff.added) {
4702 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004703 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004704 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004705 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004706 } catch (Exception e) {
4707 loge("Exception adding interface: " + e);
4708 }
4709 }
4710 for (String iface : interfaceDiff.removed) {
4711 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004712 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004713 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004714 mNetd.removeInterfaceFromNetwork(iface, netId);
4715 } catch (Exception e) {
4716 loge("Exception removing interface: " + e);
4717 }
4718 }
4719 }
4720
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004721 /**
4722 * Have netd update routes from oldLp to newLp.
4723 * @return true if routes changed between oldLp and newLp
4724 */
4725 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004726 // Compare the route diff to determine which routes should be added and removed.
4727 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4728 oldLp != null ? oldLp.getAllRoutes() : null,
4729 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730
4731 // add routes before removing old in case it helps with continuous connectivity
4732
Chalard Jean4d660112018-06-04 16:52:49 +09004733 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004734 for (RouteInfo route : routeDiff.added) {
4735 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004736 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004737 try {
4738 mNetd.addRoute(netId, route);
4739 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004740 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4741 loge("Exception in addRoute for non-gateway: " + e);
4742 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 }
4744 }
4745 for (RouteInfo route : routeDiff.added) {
4746 if (route.hasGateway() == false) 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.getGateway() instanceof Inet4Address) || VDBG) {
4752 loge("Exception in addRoute for gateway: " + e);
4753 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 }
4755 }
4756
4757 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004758 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 try {
4760 mNetd.removeRoute(netId, route);
4761 } catch (Exception e) {
4762 loge("Exception in removeRoute: " + e);
4763 }
4764 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004765 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 }
Erik Kline41368502015-06-17 13:19:54 +09004767
Erik Kline94887872016-04-05 13:30:49 +09004768 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4769 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4770 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004771 }
Erik Kline94887872016-04-05 13:30:49 +09004772
Erik Kline1742fe12017-12-13 19:40:49 +09004773 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4774 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4775
Erik Klinea24d4592018-01-11 21:07:29 +09004776 if (DBG) {
4777 final Collection<InetAddress> dnses = newLp.getDnsServers();
4778 log("Setting DNS servers for network " + netId + " to " + dnses);
4779 }
Erik Kline94887872016-04-05 13:30:49 +09004780 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004781 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004782 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004783 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004784 }
Erik Kline4edba012017-04-07 15:29:29 +09004785 }
4786
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004787 private String getNetworkPermission(NetworkCapabilities nc) {
4788 // TODO: make these permission strings AIDL constants instead.
4789 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4790 return NetworkManagementService.PERMISSION_SYSTEM;
4791 }
4792 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4793 return NetworkManagementService.PERMISSION_NETWORK;
4794 }
4795 return null;
4796 }
4797
Paul Jensen3d194ea2015-06-16 14:27:36 -04004798 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004799 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4800 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4801 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004802 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004803 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004804 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004805 // Don't complain for VPNs since they're not driven by requests and there is no risk of
4806 // causing a connect/teardown loop.
4807 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
4808 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004809 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004810 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004811 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4812 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004813 // does not cause any request (that is not a listen) currently matching that agent to
4814 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004815 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004816 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004817 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004818 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 }
4820
Paul Jensen3d194ea2015-06-16 14:27:36 -04004821 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004822 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004823 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004824 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004825 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004827 }
Paul Jensene0988542015-06-25 15:30:08 -04004828 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004829 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004830 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004831 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004832 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004833 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004834 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004835 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004836 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004837 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004838 if (nai.isSuspended()) {
4839 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4840 } else {
4841 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4842 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004843
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004844 return newNc;
4845 }
4846
4847 /**
4848 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4849 *
4850 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4851 * capabilities we manage and store in {@code nai}, such as validated status and captive
4852 * portal status)
4853 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4854 * potentially triggers rematches.
4855 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4856 * change.)
4857 *
4858 * @param oldScore score of the network before any of the changes that prompted us
4859 * to call this function.
4860 * @param nai the network having its capabilities updated.
4861 * @param nc the new network capabilities.
4862 */
4863 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4864 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4865
4866 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004867
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004868 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004869 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004870 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004871 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004872 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004873 } catch (RemoteException e) {
4874 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004875 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004876 }
4877
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004878 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004879 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004880 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004881 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004883
Chalard Jeanf213ca12018-01-16 18:43:05 +09004884 updateUids(nai, prevNc, newNc);
4885
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004886 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004887 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4888 // the change we're processing can't affect any requests, it can only affect the listens
4889 // on this network. We might have been called by rematchNetworkAndRequests when a
4890 // network changed foreground state.
4891 processListenRequests(nai, true);
4892 } else {
4893 // If the requestable capabilities have changed or the score changed, we can't have been
4894 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004895 rematchAllNetworksAndRequests(nai, oldScore);
4896 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004897 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004898
4899 // Report changes that are interesting for network statistics tracking.
4900 if (prevNc != null) {
4901 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004902 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004903 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004904 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004905 if (meteredChanged || roamingChanged) {
4906 notifyIfacesChangedForNetworkStats();
4907 }
4908 }
4909
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004910 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004911 // Tell VPNs about updated capabilities, since they may need to
4912 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004913 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004914 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004915 }
4916
Chalard Jeanf213ca12018-01-16 18:43:05 +09004917 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4918 NetworkCapabilities newNc) {
4919 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4920 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4921 if (null == prevRanges) prevRanges = new ArraySet<>();
4922 if (null == newRanges) newRanges = new ArraySet<>();
4923 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4924
4925 prevRanges.removeAll(newRanges);
4926 newRanges.removeAll(prevRangesCopy);
4927
4928 try {
4929 if (!newRanges.isEmpty()) {
4930 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4931 newRanges.toArray(addedRangesArray);
4932 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4933 }
4934 if (!prevRanges.isEmpty()) {
4935 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4936 prevRanges.toArray(removedRangesArray);
4937 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4938 }
4939 } catch (Exception e) {
4940 // Never crash!
4941 loge("Exception in updateUids: " + e);
4942 }
4943 }
4944
Hugo Benichief502882017-09-01 01:23:32 +00004945 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004946 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004947 // Ignore updates for disconnected networks
4948 return;
4949 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004950 // newLp is already a defensive copy.
4951 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004952 if (VDBG) {
4953 log("Update of LinkProperties for " + nai.name() +
4954 "; created=" + nai.created +
4955 "; everConnected=" + nai.everConnected);
4956 }
4957 LinkProperties oldLp = nai.linkProperties;
4958 synchronized (nai) {
4959 nai.linkProperties = newLp;
4960 }
4961 if (nai.everConnected) {
4962 updateLinkProperties(nai, oldLp);
4963 }
4964 }
4965
Paul Jensenc8b9a742014-09-30 15:37:41 -04004966 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004967 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4968 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004969 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004970 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004971 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4972 }
4973 }
4974
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4976 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004977 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004978 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4979 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004980 }
4981 }
4982
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004983 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4984 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004985 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004986 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004987 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4988 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004989 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004990 sendIntent(nri.mPendingIntent, intent);
4991 }
4992 // else not handled
4993 }
4994
4995 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4996 mPendingIntentWakeLock.acquire();
4997 try {
4998 if (DBG) log("Sending " + pendingIntent);
4999 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5000 } catch (PendingIntent.CanceledException e) {
5001 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5002 mPendingIntentWakeLock.release();
5003 releasePendingNetworkRequest(pendingIntent);
5004 }
5005 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5006 }
5007
5008 @Override
5009 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5010 String resultData, Bundle resultExtras) {
5011 if (DBG) log("Finished sending " + pendingIntent);
5012 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005013 // Release with a delay so the receiving client has an opportunity to put in its
5014 // own request.
5015 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005016 }
5017
Chalard Jeanf19db372018-01-26 19:24:40 +09005018 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005019 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005020 if (nri.messenger == null) {
5021 return; // Default request has no msgr
5022 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005023 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005024 // TODO: check if defensive copies of data is needed.
5025 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005026 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005027 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5028 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005029 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005030 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005031 case ConnectivityManager.CALLBACK_AVAILABLE: {
5032 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5033 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5034 break;
5035 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005036 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005037 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005038 break;
5039 }
5040 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005041 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005042 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005043 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005044 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005045 break;
5046 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005047 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005048 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005049 break;
5050 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005051 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005052 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005053 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005054 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005055 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005056 String notification = ConnectivityManager.getCallbackName(notificationType);
5057 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005058 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005059 nri.messenger.send(msg);
5060 } catch (RemoteException e) {
5061 // may occur naturally in the race of binder death.
5062 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5063 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005064 }
5065
Hugo Benichidba33db2017-03-23 22:40:44 +09005066 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5067 bundle.putParcelable(t.getClass().getSimpleName(), t);
5068 }
5069
Paul Jensenc8b9a742014-09-30 15:37:41 -04005070 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005071 if (nai.numRequestNetworkRequests() != 0) {
5072 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5073 NetworkRequest nr = nai.requestAt(i);
5074 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005075 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005076 loge("Dead network still had at least " + nr);
5077 break;
5078 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005079 }
5080 nai.asyncChannel.disconnect();
5081 }
5082
Robert Greenwalt7b816022014-04-18 15:25:25 -07005083 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5084 if (oldNetwork == null) {
5085 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5086 return;
5087 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005088 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005089
5090 // If we get here it means that the last linger timeout for this network expired. So there
5091 // must be no other active linger timers, and we must stop lingering.
5092 oldNetwork.clearLingerState();
5093
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005094 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005095 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005096 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005097 } else {
5098 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005099 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5100 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005101 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005102 }
5103
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005104 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005105 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005106
Paul Jensen27b02b72014-07-14 12:03:33 -04005107 try {
5108 mNetd.setDefaultNetId(newNetwork.network.netId);
5109 } catch (Exception e) {
5110 loge("Exception setting default network :" + e);
5111 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005112
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005113 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005114 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005115 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005116 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005117 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005118 }
5119
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005120 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005121 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5122 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5123 NetworkRequest nr = nri.request;
5124 if (!nr.isListen()) continue;
5125 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5126 nai.removeRequest(nri.request.requestId);
5127 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5128 }
5129 }
5130
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005131 if (capabilitiesChanged) {
5132 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5133 }
5134
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005135 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5136 NetworkRequest nr = nri.request;
5137 if (!nr.isListen()) continue;
5138 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5139 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005140 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005141 }
5142 }
5143 }
5144
Paul Jensen2161a8e2014-09-11 11:00:39 -04005145 // Handles a network appearing or improving its score.
5146 //
5147 // - Evaluates all current NetworkRequests that can be
5148 // satisfied by newNetwork, and reassigns to newNetwork
5149 // any such requests for which newNetwork is the best.
5150 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005151 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005152 // needed. A network is needed if it is the best network for
5153 // one or more NetworkRequests, or if it is a VPN.
5154 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005155 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005156 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005157 //
5158 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5159 // networks that have no chance (i.e. even if validated)
5160 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005161 //
5162 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5163 // it does not remove NetworkRequests that other Networks could better satisfy.
5164 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5165 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5166 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005167 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005168 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005169 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5170 // performed to tear down unvalidated networks that have no chance (i.e. even if
5171 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005172 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005173 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005174 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005175 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005176 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005177 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005178
5179 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5180 final int score = newNetwork.getCurrentScore();
5181
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005182 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005183
Paul Jensen2161a8e2014-09-11 11:00:39 -04005184 // Find and migrate to this Network any NetworkRequests for
5185 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005186 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5187 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005188 NetworkCapabilities nc = newNetwork.networkCapabilities;
5189 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005190 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005191 // Process requests in the first pass and listens in the second pass. This allows us to
5192 // change a network's capabilities depending on which requests it has. This is only
5193 // correct if the change in capabilities doesn't affect whether the network satisfies
5194 // requests or not, and doesn't affect the network's score.
5195 if (nri.request.isListen()) continue;
5196
Hugo Benichicd952782017-09-20 11:20:14 +09005197 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005198 final boolean satisfies = newNetwork.satisfies(nri.request);
5199 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005200 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005201 log("Network " + newNetwork.name() + " was already satisfying" +
5202 " request " + nri.request.requestId + ". No change.");
5203 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005204 keep = true;
5205 continue;
5206 }
5207
5208 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005209 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005210 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005211 // next check if it's better than any current network we're using for
5212 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213 if (VDBG) {
5214 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005215 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005216 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005217 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005218 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005219 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005220 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005221 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005222 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005223 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005224 affectedNetworks.add(currentNetwork);
5225 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005226 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005228 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005229 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005230 if (!newNetwork.addRequest(nri.request)) {
5231 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5232 }
5233 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005234 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005235 // Tell NetworkFactories about the new score, so they can stop
5236 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005237 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005238 // network. Think about if there is a way to reduce this. Push
5239 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005240 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005241 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005243 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005244 if (currentNetwork != null) {
5245 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5246 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 }
5248 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005249 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005250 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5251 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005252 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005253 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5254 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5255 // This means this code doesn't have to handle the case where "currentNetwork" no
5256 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5257 if (DBG) {
5258 log("Network " + newNetwork.name() + " stopped satisfying" +
5259 " request " + nri.request.requestId);
5260 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005261 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005262 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005263 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005264 sendUpdatedScoreToFactories(nri.request, 0);
5265 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005266 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5267 newNetwork.name() +
5268 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005269 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005270 // TODO: Technically, sending CALLBACK_LOST here is
5271 // incorrect if there is a replacement network currently
5272 // connected that can satisfy nri, which is a request
5273 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005274 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5275 // so this code is only incorrect for a network that loses
5276 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005277 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005278 }
5279 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005280 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005281 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005282 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005283 makeDefault(newNetwork);
5284 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005285 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005286 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005287 // Have a new default network, release the transition wakelock in
5288 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005289 }
5290
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005291 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5292 Slog.wtf(TAG, String.format(
5293 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005294 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005295 }
5296 if (newNetwork.getCurrentScore() != score) {
5297 Slog.wtf(TAG, String.format(
5298 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005299 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005300 }
5301
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005302 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005303 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5304 // If the network went from background to foreground or vice versa, we need to update
5305 // its foreground state. It is safe to do this after rematching the requests because
5306 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5307 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005308 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005309 } else {
5310 processListenRequests(newNetwork, false);
5311 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005312
Paul Jensencf4c2c62015-07-01 14:16:32 -04005313 // do this after the default net is switched, but
5314 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005315 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005316
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005317 // Linger any networks that are no longer needed. This should be done after sending the
5318 // available callback for newNetwork.
5319 for (NetworkAgentInfo nai : affectedNetworks) {
5320 updateLingerState(nai, now);
5321 }
5322 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5323 // does not need to be done in any particular order.
5324 updateLingerState(newNetwork, now);
5325
Paul Jensencf4c2c62015-07-01 14:16:32 -04005326 if (isNewDefault) {
5327 // Maintain the illusion: since the legacy API only
5328 // understands one network at a time, we must pretend
5329 // that the current default network disconnected before
5330 // the new one connected.
5331 if (oldDefaultNetwork != null) {
5332 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5333 oldDefaultNetwork, true);
5334 }
5335 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5336 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5337 notifyLockdownVpn(newNetwork);
5338 }
5339
Robert Greenwalt7b816022014-04-18 15:25:25 -07005340 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005341 // Notify battery stats service about this network, both the normal
5342 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005343 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005344 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005345 final IBatteryStats bs = BatteryStatsService.getService();
5346 final int type = newNetwork.networkInfo.getType();
5347
5348 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5349 bs.noteNetworkInterfaceType(baseIface, type);
5350 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5351 final String stackedIface = stacked.getInterfaceName();
5352 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005353 }
5354 } catch (RemoteException ignored) {
5355 }
5356
Robert Greenwalt152ed372014-12-17 17:19:53 -08005357 // This has to happen after the notifyNetworkCallbacks as that tickles each
5358 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005359 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005360 // and will generally do a dns request so they can ensureRouteToHost and if
5361 // they do that before the callbacks happen they'll use the default network.
5362 //
5363 // TODO: Is there still a race here? We send the broadcast
5364 // after sending the callback, but if the app can receive the
5365 // broadcast before the callback, it might still break.
5366 //
5367 // This *does* introduce a race where if the user uses the new api
5368 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5369 // they may get old info. Reverse this after the old startUsing api is removed.
5370 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005371 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5372 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005373 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005374 // legacy type tracker filters out repeat adds
5375 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5376 }
5377 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005378
5379 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5380 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5381 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5382 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5383 if (newNetwork.isVPN()) {
5384 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5385 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005386 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005387 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5388 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005389 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005390 if (nai.getLingerExpiry() > 0) {
5391 // This network has active linger timers and no requests, but is not
5392 // lingering. Linger it.
5393 //
5394 // One way (the only way?) this can happen if this network is unvalidated
5395 // and became unneeded due to another network improving its score to the
5396 // point where this network will no longer be able to satisfy any requests
5397 // even if it validates.
5398 updateLingerState(nai, now);
5399 } else {
5400 if (DBG) log("Reaping " + nai.name());
5401 teardownUnneededNetwork(nai);
5402 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005403 }
5404 }
5405 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005406 }
5407
Paul Jensen1c7ba022015-06-16 14:27:36 -04005408 /**
5409 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5410 * being disconnected.
5411 * @param changed If only one Network's score or capabilities have been modified since the last
5412 * time this function was called, pass this Network in this argument, otherwise pass
5413 * null.
5414 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5415 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5416 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5417 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5418 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005419 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005420 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005421 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5422 // to avoid the slowness. It is not simply enough to process just "changed", for
5423 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005424 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005425
5426 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5427 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5428 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005429 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005430 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005431 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005432 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005433 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5434 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5435 // Rematch higher scoring networks first to prevent requests first matching a lower
5436 // scoring network and then a higher scoring network, which could produce multiple
5437 // callbacks and inadvertently unlinger networks.
5438 Arrays.sort(nais);
5439 for (NetworkAgentInfo nai : nais) {
5440 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005441 // Only reap the last time through the loop. Reaping before all rematching
5442 // is complete could incorrectly teardown a network that hasn't yet been
5443 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005444 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005445 : ReapUnvalidatedNetworks.REAP,
5446 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005447 }
5448 }
5449 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005450
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005451 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005452 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005453 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005454 // For now only update icons for default connection.
5455 // TODO: Update WiFi and cellular icons separately. b/17237507
5456 if (!isDefaultNetwork(nai)) return;
5457
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005458 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005459 // Don't repeat publish.
5460 if (newInetCondition == mDefaultInetConditionPublished) return;
5461
5462 mDefaultInetConditionPublished = newInetCondition;
5463 sendInetConditionBroadcast(nai.networkInfo);
5464 }
5465
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005466 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005467 synchronized (mVpns) {
5468 if (mLockdownTracker != null) {
5469 if (nai != null && nai.isVPN()) {
5470 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5471 } else {
5472 mLockdownTracker.onNetworkInfoChanged();
5473 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005474 }
5475 }
5476 }
5477
Robert Greenwalt7b816022014-04-18 15:25:25 -07005478 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005479 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005480 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005481 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005482 synchronized (networkAgent) {
5483 oldInfo = networkAgent.networkInfo;
5484 networkAgent.networkInfo = newInfo;
5485 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005486 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005487
Robert Greenwalt7b816022014-04-18 15:25:25 -07005488 if (DBG) {
5489 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5490 (oldInfo == null ? "null" : oldInfo.getState()) +
5491 " to " + state);
5492 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005493
Robin Lee585e2482016-05-01 23:00:00 +01005494 if (!networkAgent.created
5495 && (state == NetworkInfo.State.CONNECTED
5496 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005497
5498 // A network that has just connected has zero requests and is thus a foreground network.
5499 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5500
Robert Greenwalt7b816022014-04-18 15:25:25 -07005501 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005502 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005503 if (networkAgent.isVPN()) {
5504 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005505 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5506 (networkAgent.networkMisc == null ||
5507 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005508 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005509 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005510 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005511 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005512 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005513 loge("Error creating network " + networkAgent.network.netId + ": "
5514 + e.getMessage());
5515 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005516 }
Paul Jenseneec75412014-08-04 12:21:19 -04005517 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005518 }
5519
5520 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5521 networkAgent.everConnected = true;
5522
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005523 if (networkAgent.linkProperties == null) {
5524 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5525 }
5526
Erik Kline736353a2018-03-21 07:18:33 -07005527 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005528 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005529
Paul Jensenca8f16a2014-05-09 12:47:55 -04005530 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005531 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005532
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005533 if (networkAgent.isVPN()) {
5534 // Temporarily disable the default proxy (not global).
Chalard Jean52c2aa72018-06-07 16:44:04 +09005535 synchronized (mProxyTracker.mProxyLock) {
5536 if (!mProxyTracker.mDefaultProxyDisabled) {
5537 mProxyTracker.mDefaultProxyDisabled = true;
5538 if (mProxyTracker.mGlobalProxy == null
5539 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005540 mProxyTracker.sendProxyBroadcast(null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005541 }
5542 }
5543 }
5544 // TODO: support proxy per network.
5545 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005546
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005547 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5548 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5549 // capabilities, so it only needs to be done once on initial connect, not every time the
5550 // network's capabilities change. Note that we do this before rematching the network,
5551 // so we could decide to tear it down immediately afterwards. That's fine though - on
5552 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5553 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005554 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005555
Paul Jensen2161a8e2014-09-11 11:00:39 -04005556 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005557 final long now = SystemClock.elapsedRealtime();
5558 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005559
5560 // This has to happen after matching the requests, because callbacks are just requests.
5561 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005562 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005563 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005564 if (networkAgent.isVPN()) {
Chalard Jean52c2aa72018-06-07 16:44:04 +09005565 synchronized (mProxyTracker.mProxyLock) {
5566 if (mProxyTracker.mDefaultProxyDisabled) {
5567 mProxyTracker.mDefaultProxyDisabled = false;
5568 if (mProxyTracker.mGlobalProxy == null
5569 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005570 mProxyTracker.sendProxyBroadcast(mProxyTracker.mDefaultProxy);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005571 }
5572 }
5573 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005574 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005575 }
Chalard Jean392971c2018-05-11 20:19:20 +09005576 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005577 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5578 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005579 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005580 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005581 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005582 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005583 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5584 networkAgent.networkCapabilities);
5585 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5586 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005587 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5588 ConnectivityManager.CALLBACK_SUSPENDED :
5589 ConnectivityManager.CALLBACK_RESUMED));
5590 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005591 }
5592 }
5593
Robert Greenwaltac96c522014-06-03 16:43:57 -07005594 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005595 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005596 if (score < 0) {
5597 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5598 "). Bumping score to min of 0");
5599 score = 0;
5600 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005601
Paul Jensen2161a8e2014-09-11 11:00:39 -04005602 final int oldScore = nai.getCurrentScore();
5603 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005604
Paul Jensen85cf78e2015-06-25 13:25:07 -04005605 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005606
Paul Jensenc8b9a742014-09-30 15:37:41 -04005607 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005608 }
5609
Erik Klinec75d4fa2017-02-15 19:59:17 +09005610 // Notify only this one new request of the current state. Transfer all the
5611 // current state by calling NetworkCapabilities and LinkProperties callbacks
5612 // so that callers can be guaranteed to have as close to atomicity in state
5613 // transfer as can be supported by this current API.
5614 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005615 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005616 if (nri.mPendingIntent != null) {
5617 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5618 // Attempt no subsequent state pushes where intents are involved.
5619 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005620 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005621
5622 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005623 }
5624
Robert Greenwalt8d482522015-06-24 13:23:42 -07005625 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005626 // The NetworkInfo we actually send out has no bearing on the real
5627 // state of affairs. For example, if the default connection is mobile,
5628 // and a request for HIPRI has just gone away, we need to pretend that
5629 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5630 // the state to DISCONNECTED, even though the network is of type MOBILE
5631 // and is still connected.
5632 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5633 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005634 if (state != DetailedState.DISCONNECTED) {
5635 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005636 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005637 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005638 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005639 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5640 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5641 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5642 if (info.isFailover()) {
5643 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5644 nai.networkInfo.setFailover(false);
5645 }
5646 if (info.getReason() != null) {
5647 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5648 }
5649 if (info.getExtraInfo() != null) {
5650 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5651 }
5652 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005653 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005654 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005655 if (newDefaultAgent != null) {
5656 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5657 newDefaultAgent.networkInfo);
5658 } else {
5659 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5660 }
5661 }
5662 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5663 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005664 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005665 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005666 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005667 }
5668 }
5669 }
5670
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005671 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005672 if (VDBG) {
5673 String notification = ConnectivityManager.getCallbackName(notifyType);
5674 log("notifyType " + notification + " for " + networkAgent.name());
5675 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005676 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5677 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005678 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5679 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005680 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5681 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005682 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005683 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005684 } else {
5685 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5686 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005687 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005688 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005689
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005690 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5691 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5692 }
5693
Jeff Sharkey69736342014-12-08 14:50:12 -08005694 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005695 * Returns the list of all interfaces that could be used by network traffic that does not
5696 * explicitly specify a network. This includes the default network, but also all VPNs that are
5697 * currently connected.
5698 *
5699 * Must be called on the handler thread.
5700 */
5701 private Network[] getDefaultNetworks() {
5702 ArrayList<Network> defaultNetworks = new ArrayList<>();
5703 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5704 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5705 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5706 defaultNetworks.add(nai.network);
5707 }
5708 }
5709 return defaultNetworks.toArray(new Network[0]);
5710 }
5711
5712 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005713 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5714 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005715 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005716 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005717 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005718 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005719 } catch (Exception ignored) {
5720 }
5721 }
5722
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005723 @Override
5724 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005725 int user = UserHandle.getUserId(Binder.getCallingUid());
5726 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005727 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005728 return mVpns.get(user).addAddress(address, prefixLength);
5729 }
5730 }
5731
5732 @Override
5733 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005734 int user = UserHandle.getUserId(Binder.getCallingUid());
5735 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005736 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005737 return mVpns.get(user).removeAddress(address, prefixLength);
5738 }
5739 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005740
5741 @Override
5742 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005743 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005744 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005745 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005746 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005747 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005748 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005749 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005750 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005751 }
5752 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005753 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005754
5755 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005756 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005757 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005758 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005759 }
5760
5761 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005762 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5763 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5764 enforceKeepalivePermission();
5765 mKeepaliveTracker.startNattKeepalive(
5766 getNetworkAgentInfoForNetwork(network),
5767 intervalSeconds, messenger, binder,
5768 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5769 }
5770
5771 @Override
5772 public void stopKeepalive(Network network, int slot) {
5773 mHandler.sendMessage(mHandler.obtainMessage(
5774 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5775 }
5776
5777 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005778 public void factoryReset() {
5779 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005780
5781 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5782 return;
5783 }
5784
Robin Lee3b3dd942015-05-12 18:14:58 +01005785 final int userId = UserHandle.getCallingUserId();
5786
Stuart Scottf1fb3972015-04-02 18:00:02 -07005787 // Turn airplane mode off
5788 setAirplaneMode(false);
5789
Stuart Scotte3e314d2015-04-20 14:07:45 -07005790 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5791 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005792 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005793 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005794 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005795 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005796 }
5797
Stuart Scotte3e314d2015-04-20 14:07:45 -07005798 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005799 // Remove always-on package
5800 synchronized (mVpns) {
5801 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5802 if (alwaysOnPackage != null) {
5803 setAlwaysOnVpnPackage(userId, null, false);
5804 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5805 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005806
Hugo Benichi69744342017-11-27 10:57:16 +09005807 // Turn Always-on VPN off
5808 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5809 final long ident = Binder.clearCallingIdentity();
5810 try {
5811 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5812 mLockdownEnabled = false;
5813 setLockdownTracker(null);
5814 } finally {
5815 Binder.restoreCallingIdentity(ident);
5816 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005817 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005818
Hugo Benichi69744342017-11-27 10:57:16 +09005819 // Turn VPN off
5820 VpnConfig vpnConfig = getVpnConfig(userId);
5821 if (vpnConfig != null) {
5822 if (vpnConfig.legacy) {
5823 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5824 } else {
5825 // Prevent this app (packagename = vpnConfig.user) from initiating
5826 // VPN connections in the future without user intervention.
5827 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005828
Hugo Benichi69744342017-11-27 10:57:16 +09005829 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5830 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005831 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005832 }
5833 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005834
5835 Settings.Global.putString(mContext.getContentResolver(),
5836 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005837 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005838
Ricky Wai44dcbde2018-01-23 04:09:45 +00005839 @Override
5840 public byte[] getNetworkWatchlistConfigHash() {
5841 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5842 if (nwm == null) {
5843 loge("Unable to get NetworkWatchlistManager");
5844 return null;
5845 }
5846 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5847 return nwm.getWatchlistConfigHash();
5848 }
5849
Paul Jensencf4c2c62015-07-01 14:16:32 -04005850 @VisibleForTesting
5851 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5852 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5853 return new NetworkMonitor(context, handler, nai, defaultRequest);
5854 }
Erik Kline48f12f22016-04-14 17:30:59 +09005855
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005856 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005857 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5858 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005859 }
5860
5861 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005862 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5863 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5864 }
5865
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005866 @VisibleForTesting
5867 public boolean hasService(String name) {
5868 return ServiceManager.checkService(name) != null;
5869 }
5870
Hugo Benichi64901e52017-10-19 14:42:40 +09005871 @VisibleForTesting
5872 protected IpConnectivityMetrics.Logger metricsLogger() {
5873 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5874 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005875 }
5876
5877 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005878 int[] transports = nai.networkCapabilities.getTransportTypes();
5879 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005880 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005881
5882 private static boolean toBool(int encodedBoolean) {
5883 return encodedBoolean != 0; // Only 0 means false.
5884 }
5885
5886 private static int encodeBool(boolean b) {
5887 return b ? 1 : 0;
5888 }
mswest46386886f2018-03-12 10:34:34 -07005889
5890 @Override
5891 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5892 FileDescriptor err, String[] args, ShellCallback callback,
5893 ResultReceiver resultReceiver) {
5894 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5895 }
5896
5897 private class ShellCmd extends ShellCommand {
5898
5899 @Override
5900 public int onCommand(String cmd) {
5901 if (cmd == null) {
5902 return handleDefaultCommands(cmd);
5903 }
5904 final PrintWriter pw = getOutPrintWriter();
5905 try {
5906 switch (cmd) {
5907 case "airplane-mode":
5908 final String action = getNextArg();
5909 if ("enable".equals(action)) {
5910 setAirplaneMode(true);
5911 return 0;
5912 } else if ("disable".equals(action)) {
5913 setAirplaneMode(false);
5914 return 0;
5915 } else if (action == null) {
5916 final ContentResolver cr = mContext.getContentResolver();
5917 final int enabled = Settings.Global.getInt(cr,
5918 Settings.Global.AIRPLANE_MODE_ON);
5919 pw.println(enabled == 0 ? "disabled" : "enabled");
5920 return 0;
5921 } else {
5922 onHelp();
5923 return -1;
5924 }
5925 default:
5926 return handleDefaultCommands(cmd);
5927 }
5928 } catch (Exception e) {
5929 pw.println(e);
5930 }
5931 return -1;
5932 }
5933
5934 @Override
5935 public void onHelp() {
5936 PrintWriter pw = getOutPrintWriter();
5937 pw.println("Connectivity service commands:");
5938 pw.println(" help");
5939 pw.println(" Print this help text.");
5940 pw.println(" airplane-mode [enable|disable]");
5941 pw.println(" Turn airplane mode on or off.");
5942 pw.println(" airplane-mode");
5943 pw.println(" Get airplane mode.");
5944 }
5945 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07005946
5947 /**
5948 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
5949 * for testing.
5950 */
5951 private Vpn enforceActiveVpnOrNetworkStackPermission() {
5952 if (checkNetworkStackPermission()) {
5953 return null;
5954 }
5955 final int uid = Binder.getCallingUid();
5956 final int user = UserHandle.getUserId(uid);
5957 synchronized (mVpns) {
5958 Vpn vpn = mVpns.get(user);
5959 try {
5960 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
5961 } catch (NullPointerException e) {
5962 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
5963 }
5964 }
5965 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
5966 + "permission");
5967 }
5968
5969 /**
5970 * @param connectionInfo the connection to resolve.
5971 * @return {@code uid} if the connection is found and the app has permission to observe it
5972 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
5973 * connection is not found.
5974 */
5975 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
5976 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
5977 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
5978 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
5979 }
5980
5981 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
5982 connectionInfo.local, connectionInfo.remote);
5983
5984 /* Filter out Uids not associated with the VPN. */
5985 if (vpn != null && !vpn.appliesToUid(uid)) {
5986 return INVALID_UID;
5987 }
5988
5989 return uid;
5990 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005991}