blob: 125c60cbc9cba9b4d1242ea283b2ad24110838f2 [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;
38
Hugo Benichia0385682017-03-22 17:07:57 +090039import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090043import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070044import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080059import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010061import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090069import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070072import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000075import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070076import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040077import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070078import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040079import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040080import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060081import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090082import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090083import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090084import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080086import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070087import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040088import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070090import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070091import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070092import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.os.Looper;
94import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070095import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070096import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090097import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070098import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070099import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700100import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800101import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900102import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900103import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700104import android.os.ShellCallback;
105import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900106import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700107import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400108import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700110import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700111import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700112import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700113import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900114import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700115import android.util.LocalLog;
116import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600117import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800118import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700119import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500120import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700121import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700122import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Wink Savilleab9321d2013-06-29 21:10:57 -0700124import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400125import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400126import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700127import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700128import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700130import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800131import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700132import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700133import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600134import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700135import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900136import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900137import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700138import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700139import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400140import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900141import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900142import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900143import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900144import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100145import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700146import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900147import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700148import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600149import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400150import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900151import com.android.server.connectivity.NetworkNotificationManager;
152import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400153import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700154import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800155import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700156import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100157import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700158import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700159import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900160import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700161import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600162
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700163import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700164
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700165import org.xmlpull.v1.XmlPullParser;
166import org.xmlpull.v1.XmlPullParserException;
167
168import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700170import java.io.FileNotFoundException;
171import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700172import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700174import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700175import java.net.InetAddress;
176import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700177import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700178import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700179import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700180import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700181import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700182import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700183import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700184import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700185import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900186import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600187import java.util.SortedSet;
188import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
190/**
191 * @hide
192 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800193public class ConnectivityService extends IConnectivityManager.Stub
194 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900195 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Erik Kline7747fd42017-05-12 16:52:48 +0900197 public static final String DIAG_ARG = "--diag";
198 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900199 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900200
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900201 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700202 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Jake Hamby786e71a2014-02-06 14:43:50 -0800204 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900205 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700206
Jeff Sharkey899223b2012-08-04 15:24:58 -0700207 // TODO: create better separation between radio types and network types
208
Robert Greenwalt42acef32009-08-12 16:08:25 -0700209 // how long to wait before switching back to a radio's default network
210 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
211 // system property that can override the above value
212 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
213 "android.telephony.apn-restore";
214
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900215 // How long to wait before putting up a "This network doesn't have an Internet connection,
216 // connect anyway?" dialog after the user selects a network that doesn't validate.
217 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
218
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900219 // Default to 30s linger time-out. Modifiable only for testing.
220 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
221 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
222 @VisibleForTesting
223 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
224
Jeremy Joslin79294842014-12-03 17:15:28 -0800225 // How long to delay to removal of a pending intent based request.
226 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
227 private final int mReleasePendingIntentDelayMs;
228
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900229 private MockableSystemProperties mSystemProperties;
230
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800231 private Tethering mTethering;
232
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700233 private final PermissionMonitor mPermissionMonitor;
234
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700235 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700236
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700237 @GuardedBy("mVpns")
238 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700239
Hugo Benichi69744342017-11-27 10:57:16 +0900240 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
241 // a direct call to LockdownVpnTracker.isEnabled().
242 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700243 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900244 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700245 private LockdownVpnTracker mLockdownTracker;
246
Erik Klineda4bfa82015-04-30 12:58:40 +0900247 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700249 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700250 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700253 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700255 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800256 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700257 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900258 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700259
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700260 private String mCurrentTcpBufferSizes;
261
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700262 private static final int ENABLED = 1;
263 private static final int DISABLED = 0;
264
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900265 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900266 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
267 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900268
Paul Jensenb10e37f2014-11-25 12:33:08 -0500269 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400270 // Tear down networks that have no chance (e.g. even if validated) of becoming
271 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500272 // all networks have been rematched against all NetworkRequests.
273 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400274 // Don't reap networks. This should be passed when some networks have not yet been
275 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 DONT_REAP
277 };
278
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900279 private enum UnneededFor {
280 LINGER, // Determine whether this network is unneeded and should be lingered.
281 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
282 }
283
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700284 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700285 * used internally to change our mobile data enabled flag
286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700288
289 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700290 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700291 * from one net to another. Clear happens when we get a new
292 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
293 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700294 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700295 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700296
Robert Greenwalt434203a2010-10-11 16:00:27 -0700297 /**
298 * used internally to reload global proxy settings
299 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700300 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700301
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700302 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400303 * PAC manager has received new port.
304 */
305 private static final int EVENT_PROXY_HAS_CHANGED = 16;
306
Robert Greenwalte049c232014-04-11 15:53:27 -0700307 /**
308 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700309 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700310 */
311 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
312
Robert Greenwalt7b816022014-04-18 15:25:25 -0700313 /**
314 * used internally when registering NetworkAgents
315 * obj = Messenger
316 */
317 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
318
Robert Greenwalt9258c642014-03-26 16:47:06 -0700319 /**
320 * used to add a network request
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
324
325 /**
326 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900327 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700328 * cancel it.
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
332
333 /**
334 * used to add a network listener - no request
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
338
339 /**
340 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400341 * arg1 = UID of caller
342 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700343 */
344 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
345
Robert Greenwalta67be032014-05-16 15:49:14 -0700346 /**
347 * used internally when registering NetworkFactories
348 * obj = Messenger
349 */
350 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
351
Robert Greenwalt27711812014-06-25 16:45:57 -0700352 /**
353 * used internally to expire a wakelock when transitioning
354 * from one net to another. Expire happens when we fail to find
355 * a new network (typically after 1 minute) -
356 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
357 * a replacement network.
358 */
359 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
360
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700361 /**
362 * Used internally to indicate the system is ready.
363 */
364 private static final int EVENT_SYSTEM_READY = 25;
365
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800366 /**
367 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400368 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800369 */
370 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
371
372 /**
373 * used to remove a pending intent and its associated network request.
374 * arg1 = UID of caller
375 * obj = PendingIntent
376 */
377 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
378
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900379 /**
380 * used to specify whether a network should be used even if unvalidated.
381 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
382 * arg2 = whether to remember this choice in the future (1 or 0)
383 * obj = network
384 */
385 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
386
387 /**
388 * used to ask the user to confirm a connection to an unvalidated network.
389 * obj = network
390 */
391 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700392
Erik Klineda4bfa82015-04-30 12:58:40 +0900393 /**
394 * used internally to (re)configure mobile data always-on settings.
395 */
396 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
397
Paul Jensen694f2b82015-06-17 14:15:39 -0400398 /**
399 * used to add a network listener with a pending intent
400 * obj = NetworkRequestInfo
401 */
402 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
403
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900404 /**
405 * used to specify whether a network should not be penalized when it becomes unvalidated.
406 */
407 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
408
409 /**
410 * used to trigger revalidation of a network.
411 */
412 private static final int EVENT_REVALIDATE_NETWORK = 36;
413
Erik Klinea24d4592018-01-11 21:07:29 +0900414 // Handle changes in Private DNS settings.
415 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
416
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900417 private static String eventName(int what) {
418 return sMagicDecoderRing.get(what, Integer.toString(what));
419 }
420
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900421 /** Handler thread used for both of the handlers below. */
422 @VisibleForTesting
423 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700424 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700425 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700426 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700427 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900428 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700429
Mike Lockwood0f79b542009-08-14 14:18:49 -0400430 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800431 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400432
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700433 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700434 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800435 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700436
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400438 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700439 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700440 private boolean mDefaultProxyDisabled = false;
441
Robert Greenwalt434203a2010-10-11 16:00:27 -0700442 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400443 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700444
Jason Monk602b2322013-07-03 17:04:33 -0400445 private PacManager mPacManager = null;
446
Erik Klineda4bfa82015-04-30 12:58:40 +0900447 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700448
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400449 private UserManager mUserManager;
450
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700451 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700452 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700453
Robert Greenwalt50393202011-06-21 17:26:14 -0700454 // the set of network types that can only be enabled by system/sig apps
455 List mProtectedNetworks;
456
John Spurlockbf991a82013-06-24 14:20:23 -0400457 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700458
Wink Savilleab9321d2013-06-29 21:10:57 -0700459 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400460
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900461 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900462 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900463 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900464
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700465 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800466 private static final int MIN_NET_ID = 100; // some reserved marks
467 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700468 private int mNextNetId = MIN_NET_ID;
469
Robert Greenwalt34524f02014-05-18 16:22:10 -0700470 // sequence number of NetworkRequests
471 private int mNextNetworkRequestId = 1;
472
Erik Kline7523eb32015-07-09 18:24:03 +0900473 // NetworkRequest activity String log entries.
474 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
475 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
476
Hugo Benichic2ae2872016-07-11 11:05:12 +0900477 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900478 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900479 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
480
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900481 private static final int MAX_WAKELOCK_LOGS = 20;
482 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900483 private int mTotalWakelockAcquisitions = 0;
484 private int mTotalWakelockReleases = 0;
485 private long mTotalWakelockDurationMs = 0;
486 private long mMaxWakelockDurationMs = 0;
487 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900488
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
490 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 private static class ValidationLog {
492 final Network mNetwork;
493 final String mNetworkExtraInfo;
494 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700495
Paul Jensen0808eb82016-06-03 13:51:21 -0400496 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
497 mNetwork = network;
498 mNetworkExtraInfo = networkExtraInfo;
499 mLog = log;
500 }
501 }
502 private final ArrayDeque<ValidationLog> mValidationLogs =
503 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
504
505 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900506 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700507 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
508 mValidationLogs.removeLast();
509 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400510 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700511 }
512 }
513
Hugo Benichif9fdf872016-07-28 17:53:06 +0900514 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900515
Erik Kline065ab6e2016-10-02 18:02:14 +0900516 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900517 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900518
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900519 @VisibleForTesting
520 final MultipathPolicyTracker mMultipathPolicyTracker;
521
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 /**
523 * Implements support for the legacy "one network per network type" model.
524 *
525 * We used to have a static array of NetworkStateTrackers, one for each
526 * network type, but that doesn't work any more now that we can have,
527 * for example, more that one wifi network. This class stores all the
528 * NetworkAgentInfo objects that support a given type, but the legacy
529 * API will only see the first one.
530 *
531 * It serves two main purposes:
532 *
533 * 1. Provide information about "the network for a given type" (since this
534 * API only supports one).
535 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
536 * the first network for a given type changes, or if the default network
537 * changes.
538 */
539 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900541 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900543
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 /**
545 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
546 * Each list holds references to all NetworkAgentInfos that are used to
547 * satisfy requests for that network type.
548 *
549 * This array is built out at startup such that an unsupported network
550 * doesn't get an ArrayList instance, making this a tristate:
551 * unsupported, supported but not active and active.
552 *
553 * The actual lists are populated when we scan the network types that
554 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 *
556 * Threading model:
557 * - addSupportedType() is only called in the constructor
558 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
559 * They are therefore not thread-safe with respect to each other.
560 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
561 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
562 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565
566 public LegacyTypeTracker() {
567 mTypeLists = (ArrayList<NetworkAgentInfo>[])
568 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
569 }
570
571 public void addSupportedType(int type) {
572 if (mTypeLists[type] != null) {
573 throw new IllegalStateException(
574 "legacy list for type " + type + "already initialized");
575 }
576 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
577 }
578
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700579 public boolean isTypeSupported(int type) {
580 return isNetworkTypeValid(type) && mTypeLists[type] != null;
581 }
582
583 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 synchronized (mTypeLists) {
585 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
586 return mTypeLists[type].get(0);
587 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900589 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700590 }
591
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700595 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900597 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 }
599 }
600
601 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700602 public void add(int type, NetworkAgentInfo nai) {
603 if (!isTypeSupported(type)) {
604 return; // Invalid network type.
605 }
606 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
607
608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 return;
611 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900612 synchronized (mTypeLists) {
613 list.add(nai);
614 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900615
616 // 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 +0900617 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900618 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
620 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700621 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 }
623
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
627 if (list == null || list.isEmpty()) {
628 return;
629 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900631
Hugo Benichi78caa2582016-06-21 09:48:07 +0900632 synchronized (mTypeLists) {
633 if (!list.remove(nai)) {
634 return;
635 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 }
637
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 final DetailedState state = DetailedState.DISCONNECTED;
639
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700641 maybeLogBroadcast(nai, state, type, wasDefault);
642 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900643 }
644
645 if (!list.isEmpty() && wasFirstNetwork) {
646 if (DBG) log("Other network available for type " + type +
647 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
650 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652 }
653
654 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900655 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
656 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900658 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700659 }
660 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661
Robert Greenwalt8d482522015-06-24 13:23:42 -0700662 // send out another legacy broadcast - currently only used for suspend/unsuspend
663 // toggle
664 public void update(NetworkAgentInfo nai) {
665 final boolean isDefault = isDefaultNetwork(nai);
666 final DetailedState state = nai.networkInfo.getDetailedState();
667 for (int type = 0; type < mTypeLists.length; type++) {
668 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700669 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 final boolean isFirst = contains && (nai == list.get(0));
671 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700672 maybeLogBroadcast(nai, state, type, isDefault);
673 sendLegacyNetworkBroadcast(nai, state, type);
674 }
675 }
676 }
677
Lorenzo Colittia793a672014-07-31 23:20:17 +0900678 private String naiToString(NetworkAgentInfo nai) {
679 String name = (nai != null) ? nai.name() : "null";
680 String state = (nai.networkInfo != null) ?
681 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
682 "???/???";
683 return name + " " + state;
684 }
685
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 pw.println("mLegacyTypeTracker:");
688 pw.increaseIndent();
689 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700690 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900691 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700692 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900693 pw.println();
694 pw.println("Current state:");
695 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900696 synchronized (mTypeLists) {
697 for (int type = 0; type < mTypeLists.length; type++) {
698 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
699 for (NetworkAgentInfo nai : mTypeLists[type]) {
700 pw.println(type + " " + naiToString(nai));
701 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900702 }
703 }
704 pw.decreaseIndent();
705 pw.decreaseIndent();
706 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 }
709 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
710
Vishnu Nair5c010902017-10-26 10:08:50 -0700711 /**
712 * Helper class which parses out priority arguments and dumps sections according to their
713 * priority. If priority arguments are omitted, function calls the legacy dump command.
714 */
715 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
716 @Override
717 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
718 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
719 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
720 }
721
722 @Override
723 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
724 doDump(fd, pw, args, asProto);
725 }
726
727 @Override
728 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
729 doDump(fd, pw, args, asProto);
730 }
731 };
732
Jeff Sharkey899223b2012-08-04 15:24:58 -0700733 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700734 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900735 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
736 }
737
738 @VisibleForTesting
739 protected ConnectivityService(Context context, INetworkManagementService netManager,
740 INetworkStatsService statsService, INetworkPolicyManager policyManager,
741 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800742 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800743
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900744 mSystemProperties = getSystemProperties();
745
Hugo Benichif9fdf872016-07-28 17:53:06 +0900746 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900747 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900748 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900749 mNetworkRequests.put(mDefaultRequest, defaultNRI);
750 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900751
Chalard Jeandda156a2018-01-10 21:19:32 +0900752 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900753 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700754
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900755 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900756 mHandlerThread.start();
757 mHandler = new InternalHandler(mHandlerThread.getLooper());
758 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700759
Jeremy Joslin79294842014-12-03 17:15:28 -0800760 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
761 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
762
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900763 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900764
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700765 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700766 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800767 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700768 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900769 mPolicyManagerInternal = checkNotNull(
770 LocalServices.getService(NetworkPolicyManagerInternal.class),
771 "missing NetworkPolicyManagerInternal");
772
Jeff Sharkey82f85212012-08-24 11:17:25 -0700773 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700774 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700775
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900777 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700778 } catch (RemoteException e) {
779 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700780 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700781 }
782
783 final PowerManager powerManager = (PowerManager) context.getSystemService(
784 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700785 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
786 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
787 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800788 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700789
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700790 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700791
Wink Saville51f456f2013-04-23 14:26:51 -0700792 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900793 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700794 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700795 String[] naStrings = context.getResources().getStringArray(
796 com.android.internal.R.array.networkAttributes);
797 for (String naString : naStrings) {
798 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700799 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700800 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700801 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800802 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700803 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700804 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700805 }
Wink Saville51f456f2013-04-23 14:26:51 -0700806 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
807 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
808 n.type);
809 continue;
810 }
Wink Saville975c8482011-04-07 14:23:45 -0700811 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800812 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700813 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700814 continue;
815 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700816 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700817
Wink Saville975c8482011-04-07 14:23:45 -0700818 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700819 mNetworksDefined++;
820 } catch(Exception e) {
821 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700822 }
823 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700824
825 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
826 if (mNetConfigs[TYPE_VPN] == null) {
827 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
828 // don't need to add TYPE_VPN to mNetConfigs.
829 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
830 mNetworksDefined++; // used only in the log() statement below.
831 }
832
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900833 // Do the same for Ethernet, since it's often not specified in the configs, although many
834 // devices can use it via USB host adapters.
835 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
836 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
837 mNetworksDefined++;
838 }
839
Wink Saville5e56bc52013-07-29 15:00:57 -0700840 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700841
Robert Greenwalt50393202011-06-21 17:26:14 -0700842 mProtectedNetworks = new ArrayList<Integer>();
843 int[] protectedNetworks = context.getResources().getIntArray(
844 com.android.internal.R.array.config_protectedNetworks);
845 for (int p : protectedNetworks) {
846 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
847 mProtectedNetworks.add(p);
848 } else {
849 if (DBG) loge("Ignoring protectedNetwork " + p);
850 }
851 }
852
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900853 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
854 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700855
Erik Kline47222fc2017-04-30 19:36:15 +0900856 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800857
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700858 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
859
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700860 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700861 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100862 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700863 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700864 intentFilter.addAction(Intent.ACTION_USER_ADDED);
865 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000866 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700867 mContext.registerReceiverAsUser(
868 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000869 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
870 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900871
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700872 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700873 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700874 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700875 } catch (RemoteException e) {
876 loge("Error registering observer :" + e);
877 }
878
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 mSettingsObserver = new SettingsObserver(mContext, mHandler);
880 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800881
John Spurlockbf991a82013-06-24 14:20:23 -0400882 mDataConnectionStats = new DataConnectionStats(mContext);
883 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400884
Jason Monkdecd2952013-10-10 14:02:51 -0400885 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700886
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400887 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900888
889 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900890 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
891 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900892
893 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
894 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
895 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
896 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
897 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
898 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
899 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900900
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900901 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900902 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900903 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900904
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900905 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
906
Erik Kline1742fe12017-12-13 19:40:49 +0900907 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900908 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700910
Erik Kline47222fc2017-04-30 19:36:15 +0900911 private Tethering makeTethering() {
912 // TODO: Move other elements into @Overridden getters.
913 final TetheringDependencies deps = new TetheringDependencies();
914 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
915 IoThread.get().getLooper(), new MockableSystemProperties(),
916 deps);
917 }
918
Chalard Jeandda156a2018-01-10 21:19:32 +0900919 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900920 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900921 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900922 netCap.addCapability(NET_CAPABILITY_INTERNET);
923 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900924 if (transportType > -1) {
925 netCap.addTransportType(transportType);
926 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900927 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900928 }
929
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900930 // Used only for testing.
931 // TODO: Delete this and either:
932 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
933 // changing ContentResolver to make registerContentObserver non-final).
934 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
935 // by subclassing SettingsObserver.
936 @VisibleForTesting
937 void updateMobileDataAlwaysOn() {
938 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
939 }
940
Erik Klineda4bfa82015-04-30 12:58:40 +0900941 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900942 final boolean enable = toBool(Settings.Global.getInt(
943 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900944 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
945 if (enable == isEnabled) {
946 return; // Nothing to do.
947 }
948
949 if (enable) {
950 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900951 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900952 } else {
953 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
954 }
955 }
956
957 private void registerSettingsCallbacks() {
958 // Watch for global HTTP proxy changes.
959 mSettingsObserver.observe(
960 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
961 EVENT_APPLY_GLOBAL_HTTP_PROXY);
962
963 // Watch for whether or not to keep mobile data always on.
964 mSettingsObserver.observe(
965 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
966 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
967 }
968
Erik Klinea24d4592018-01-11 21:07:29 +0900969 private void registerPrivateDnsSettingsCallbacks() {
970 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
971 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
972 }
973 }
974
Robert Greenwalt34524f02014-05-18 16:22:10 -0700975 private synchronized int nextNetworkRequestId() {
976 return mNextNetworkRequestId++;
977 }
978
Paul Jensen67b0b072015-06-10 11:22:17 -0400979 @VisibleForTesting
980 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400981 synchronized (mNetworkForNetId) {
982 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
983 int netId = mNextNetId;
984 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
985 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500986 if (!mNetIdInUse.get(netId)) {
987 mNetIdInUse.put(netId, true);
988 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400989 }
990 }
991 }
992 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700993 }
994
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600995 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600997 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
998 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001000 state = nai.getNetworkState();
1001 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001002 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001003 final NetworkInfo info = new NetworkInfo(networkType, 0,
1004 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001005 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1006 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001007 final NetworkCapabilities capabilities = new NetworkCapabilities();
1008 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1009 !info.isRoaming());
1010 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001011 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001013 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001014 return state;
1015 } else {
1016 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001017 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001018 }
1019
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001020 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1021 if (network == null) {
1022 return null;
1023 }
1024 synchronized (mNetworkForNetId) {
1025 return mNetworkForNetId.get(network.netId);
1026 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001029 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001030 synchronized (mVpns) {
1031 if (!mLockdownEnabled) {
1032 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001033 Vpn vpn = mVpns.get(user);
1034 if (vpn != null && vpn.appliesToUid(uid)) {
1035 return vpn.getUnderlyingNetworks();
1036 }
1037 }
1038 }
1039 return null;
1040 }
1041
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001043 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001044
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001045 final Network[] networks = getVpnUnderlyingNetworks(uid);
1046 if (networks != null) {
1047 // getUnderlyingNetworks() returns:
1048 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1049 // empty array => the VPN explicitly said "no default network".
1050 // non-empty array => the VPN specified one or more default networks; we use the
1051 // first one.
1052 if (networks.length > 0) {
1053 nai = getNetworkAgentInfoForNetwork(networks[0]);
1054 } else {
1055 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001056 }
1057 }
1058
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 return nai.getNetworkState();
1061 } else {
1062 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001064 }
1065
1066 /**
1067 * Check if UID should be blocked from using the network with the given LinkProperties.
1068 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1070 boolean ignoreBlocked) {
1071 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001072 if (ignoreBlocked) {
1073 return false;
1074 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001075 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001076 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1077 if (isSystem(uid)) {
1078 return false;
1079 }
Robin Lee17e61832016-05-09 13:46:28 +01001080 synchronized (mVpns) {
1081 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1082 if (vpn != null && vpn.isBlockingUid(uid)) {
1083 return true;
1084 }
1085 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001086 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001087 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 }
1089
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001090 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001091 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1092 return;
1093 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001094 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001095 synchronized (mBlockedAppUids) {
1096 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001097 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001098 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001099 blocked = false;
1100 } else {
1101 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001102 }
1103 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001104 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1105 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1106 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001107 }
1108
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001110 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1111 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001112 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001115 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1116
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001117 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001118 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 }
Hugo Benichi69744342017-11-27 10:57:16 +09001120 synchronized (mVpns) {
1121 if (mLockdownTracker != null) {
1122 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1123 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001124 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001125 }
1126
1127 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 * Return NetworkInfo for the active (i.e., connected) network interface.
1129 * It is assumed that at most one network is active at a time. If more
1130 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001131 * @return the info for the active network, or {@code null} if none is
1132 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 enforceAccessPermission();
1137 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1141 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
1143
Paul Jensen31a94f42015-02-13 14:18:39 -05001144 @Override
1145 public Network getActiveNetwork() {
1146 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001148 }
1149
1150 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001151 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001152 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001154 }
1155
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001157 final int user = UserHandle.getUserId(uid);
1158 int vpnNetId = NETID_UNSET;
1159 synchronized (mVpns) {
1160 final Vpn vpn = mVpns.get(user);
1161 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1162 }
1163 NetworkAgentInfo nai;
1164 if (vpnNetId != NETID_UNSET) {
1165 synchronized (mNetworkForNetId) {
1166 nai = mNetworkForNetId.get(vpnNetId);
1167 }
1168 if (nai != null) return nai.network;
1169 }
1170 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 if (nai != null
1172 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1173 nai = null;
1174 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001175 return nai != null ? nai.network : null;
1176 }
1177
Lorenzo Colitti18660282016-07-04 12:55:44 +09001178 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001179 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1180 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 final int uid = Binder.getCallingUid();
1182 NetworkState state = getUnfilteredActiveNetworkState(uid);
1183 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001184 }
1185
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001188 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001190 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001191 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001192 }
1193
1194 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public NetworkInfo getNetworkInfo(int networkType) {
1196 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001198 if (getVpnUnderlyingNetworks(uid) != null) {
1199 // A VPN is active, so we may need to return one of its underlying networks. This
1200 // information is not available in LegacyTypeTracker, so we have to get it from
1201 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001203 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001204 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001205 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001206 }
1207 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001208 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001209 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001213 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001215 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001217 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001218 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001219 return state.networkInfo;
1220 } else {
1221 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001222 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001223 }
1224
1225 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 public NetworkInfo[] getAllNetworkInfo() {
1227 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001228 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001229 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1230 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 NetworkInfo info = getNetworkInfo(networkType);
1232 if (info != null) {
1233 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001236 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001239 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001240 public Network getNetworkForType(int networkType) {
1241 enforceAccessPermission();
1242 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001243 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1244 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001246 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001247 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001248 }
1249
1250 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 public Network[] getAllNetworks() {
1252 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001253 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001254 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001255 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001256 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001257 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001258 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001259 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001260 }
1261
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001262 @Override
1263 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1264 // The basic principle is: if an app's traffic could possibly go over a
1265 // network, without the app doing anything multinetwork-specific,
1266 // (hence, by "default"), then include that network's capabilities in
1267 // the array.
1268 //
1269 // In the normal case, app traffic only goes over the system's default
1270 // network connection, so that's the only network returned.
1271 //
1272 // With a VPN in force, some app traffic may go into the VPN, and thus
1273 // over whatever underlying networks the VPN specifies, while other app
1274 // traffic may go over the system default network (e.g.: a split-tunnel
1275 // VPN, or an app disallowed by the VPN), so the set of networks
1276 // returned includes the VPN's underlying networks and the system
1277 // default.
1278 enforceAccessPermission();
1279
1280 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1281
1282 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001283 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001284 if (nc != null) {
1285 result.put(nai.network, nc);
1286 }
1287
Hugo Benichi69744342017-11-27 10:57:16 +09001288 synchronized (mVpns) {
1289 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001290 Vpn vpn = mVpns.get(userId);
1291 if (vpn != null) {
1292 Network[] networks = vpn.getUnderlyingNetworks();
1293 if (networks != null) {
1294 for (Network network : networks) {
1295 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001296 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001297 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001298 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001299 }
1300 }
1301 }
1302 }
1303 }
1304 }
1305
1306 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1307 out = result.values().toArray(out);
1308 return out;
1309 }
1310
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001311 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001312 public boolean isNetworkSupported(int networkType) {
1313 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001314 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001315 }
1316
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001317 /**
1318 * Return LinkProperties for the active (i.e., connected) default
1319 * network interface. It is assumed that at most one default network
1320 * is active at a time. If more than one is active, it is indeterminate
1321 * which will be returned.
1322 * @return the ip properties for the active network, or {@code null} if
1323 * none is active
1324 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001325 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001326 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001327 enforceAccessPermission();
1328 final int uid = Binder.getCallingUid();
1329 NetworkState state = getUnfilteredActiveNetworkState(uid);
1330 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001331 }
1332
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001333 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001334 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001335 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1337 if (nai != null) {
1338 synchronized (nai) {
1339 return new LinkProperties(nai.linkProperties);
1340 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001341 }
1342 return null;
1343 }
1344
Robert Greenwalt12e67352014-05-13 21:41:06 -07001345 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001346 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001347 public LinkProperties getLinkProperties(Network network) {
1348 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001349 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1350 }
1351
1352 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1353 if (nai == null) {
1354 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001355 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001356 synchronized (nai) {
1357 return new LinkProperties(nai.linkProperties);
1358 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001359 }
1360
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001361 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001362 if (nai != null) {
1363 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001364 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001365 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1366 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001367 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001368 }
1369 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001370 return null;
1371 }
1372
1373 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001374 public NetworkCapabilities getNetworkCapabilities(Network network) {
1375 enforceAccessPermission();
1376 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1377 }
1378
Chalard Jeanb552c462018-02-21 18:43:54 +09001379 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1380 NetworkCapabilities nc, int callerPid, int callerUid) {
1381 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001382 return new NetworkCapabilities(nc).setUids(null);
1383 }
1384
Chalard Jeanb552c462018-02-21 18:43:54 +09001385 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1386 if (!checkSettingsPermission()) {
1387 nc.setSingleUid(Binder.getCallingUid());
1388 }
1389 }
1390
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001391 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001392 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001393 // Require internal since we're handing out IMSI details
1394 enforceConnectivityInternalPermission();
1395
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001396 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001397 for (Network network : getAllNetworks()) {
1398 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1399 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001400 // TODO (b/73321673) : NetworkState contains a copy of the
1401 // NetworkCapabilities, which may contain UIDs of apps to which the
1402 // network applies. Should the UIDs be cleared so as not to leak or
1403 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001404 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001405 }
1406 }
1407 return result.toArray(new NetworkState[result.size()]);
1408 }
1409
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001410 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001411 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001412 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001413 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1414 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1415 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001416 }
1417
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001418 @Override
1419 public boolean isActiveNetworkMetered() {
1420 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001421
Eric Enslenc81ef192018-02-07 18:03:53 -08001422 final int uid = Binder.getCallingUid();
1423 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001424 if (caps != null) {
1425 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1426 } else {
1427 // Always return the most conservative value
1428 return true;
1429 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001430 }
1431
Jeff Sharkey216c1812012-08-05 14:29:23 -07001432 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1433 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001434 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001435 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001436 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001437 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001438 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001439
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001440 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 * Ensure that a network route exists to deliver traffic to the specified
1442 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001443 * @param networkType the type of the network over which traffic to the
1444 * specified host is to be routed
1445 * @param hostAddress the IP address of the host to which the route is
1446 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 * @return {@code true} on success, {@code false} on failure
1448 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001449 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001452 if (mProtectedNetworks.contains(networkType)) {
1453 enforceConnectivityInternalPermission();
1454 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001455
Chad Brubakerc0234532014-02-14 13:24:29 -08001456 InetAddress addr;
1457 try {
1458 addr = InetAddress.getByAddress(hostAddress);
1459 } catch (UnknownHostException e) {
1460 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1461 return false;
1462 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001465 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 return false;
1467 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001468
1469 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1470 if (nai == null) {
1471 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1472 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1473 } else {
1474 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1475 }
1476 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001477 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001478
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001479 DetailedState netState;
1480 synchronized (nai) {
1481 netState = nai.networkInfo.getDetailedState();
1482 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001483
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001484 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001485 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001486 log("requestRouteToHostAddress on down network "
1487 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001488 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001489 }
1490 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001492
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001493 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001494 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001495 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001496 LinkProperties lp;
1497 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001498 synchronized (nai) {
1499 lp = nai.linkProperties;
1500 netId = nai.network.netId;
1501 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001502 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001503 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1504 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001505 } finally {
1506 Binder.restoreCallingIdentity(token);
1507 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001508 }
1509
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001510 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001511 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001512 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001513 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001514 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001515 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001516 if (bestRoute.getGateway().equals(addr)) {
1517 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001518 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001519 } else {
1520 // if we will connect to this through another route, add a direct route
1521 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001522 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001523 }
1524 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001525 if (DBG) log("Adding legacy route " + bestRoute +
1526 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001527 try {
1528 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1529 } catch (Exception e) {
1530 // never crash - catch them all
1531 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001532 return false;
1533 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001534 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536
Jeff Sharkey75d31892018-01-18 22:01:59 +09001537 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001538 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001539 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001540 // TODO: notify UID when it has requested targeted updates
1541 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001542 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001543 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001544 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001545 if (restrictBackground) {
1546 log("onRestrictBackgroundChanged(true): disabling tethering");
1547 mTethering.untetherAll();
1548 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001549 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001550 };
1551
Robin Lee3b3dd942015-05-12 18:14:58 +01001552 /**
1553 * Require that the caller is either in the same user or has appropriate permission to interact
1554 * across users.
1555 *
1556 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1557 */
1558 private void enforceCrossUserPermission(int userId) {
1559 if (userId == UserHandle.getCallingUserId()) {
1560 // Not a cross-user call.
1561 return;
1562 }
1563 mContext.enforceCallingOrSelfPermission(
1564 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1565 "ConnectivityService");
1566 }
1567
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001568 private void enforceInternetPermission() {
1569 mContext.enforceCallingOrSelfPermission(
1570 android.Manifest.permission.INTERNET,
1571 "ConnectivityService");
1572 }
1573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001575 mContext.enforceCallingOrSelfPermission(
1576 android.Manifest.permission.ACCESS_NETWORK_STATE,
1577 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
1580 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001581 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
Charles He36738632017-05-15 17:07:18 +01001584 private void enforceSettingsPermission() {
1585 mContext.enforceCallingOrSelfPermission(
1586 android.Manifest.permission.NETWORK_SETTINGS,
1587 "ConnectivityService");
1588 }
1589
Chalard Jeanb552c462018-02-21 18:43:54 +09001590 private boolean checkSettingsPermission() {
1591 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1592 android.Manifest.permission.NETWORK_SETTINGS);
1593 }
1594
1595 private boolean checkSettingsPermission(int pid, int uid) {
1596 return PERMISSION_GRANTED == mContext.checkPermission(
1597 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1598 }
1599
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001600 private void enforceTetherAccessPermission() {
1601 mContext.enforceCallingOrSelfPermission(
1602 android.Manifest.permission.ACCESS_NETWORK_STATE,
1603 "ConnectivityService");
1604 }
1605
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001606 private void enforceConnectivityInternalPermission() {
1607 mContext.enforceCallingOrSelfPermission(
1608 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1609 "ConnectivityService");
1610 }
1611
Hugo Benichi514da602016-07-19 15:59:27 +09001612 private void enforceConnectivityRestrictedNetworksPermission() {
1613 try {
1614 mContext.enforceCallingOrSelfPermission(
1615 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1616 "ConnectivityService");
1617 return;
1618 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1619 enforceConnectivityInternalPermission();
1620 }
1621
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001622 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001623 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001624 }
1625
Lorenzo Colitti18660282016-07-04 12:55:44 +09001626 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001627 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001628 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001629 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001630 }
1631
1632 private void sendInetConditionBroadcast(NetworkInfo info) {
1633 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1634 }
1635
Wink Saville628b0852011-08-04 15:01:58 -07001636 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001637 synchronized (mVpns) {
1638 if (mLockdownTracker != null) {
1639 info = new NetworkInfo(info);
1640 mLockdownTracker.augmentNetworkInfo(info);
1641 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001642 }
1643
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001644 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001646 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (info.isFailover()) {
1648 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1649 info.setFailover(false);
1650 }
1651 if (info.getReason() != null) {
1652 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1653 }
1654 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001655 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1656 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001658 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001659 return intent;
1660 }
1661
1662 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1663 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1664 }
1665
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001666 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001667 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1668 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1669 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001670 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001671 final long ident = Binder.clearCallingIdentity();
1672 try {
1673 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1674 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1675 } finally {
1676 Binder.restoreCallingIdentity(ident);
1677 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001678 }
1679
Mike Lockwood0f79b542009-08-14 14:18:49 -04001680 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001681 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001682 if (!mSystemReady) {
1683 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001684 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001686 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001687 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001688 }
1689
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001690 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001691 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001692 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001693 final NetworkInfo ni = intent.getParcelableExtra(
1694 ConnectivityManager.EXTRA_NETWORK_INFO);
1695 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1696 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001698 } else {
1699 BroadcastOptions opts = BroadcastOptions.makeBasic();
1700 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1701 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001702 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001703 final IBatteryStats bs = BatteryStatsService.getService();
1704 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001705 bs.noteConnectivityChanged(intent.getIntExtra(
1706 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1707 ni != null ? ni.getState().toString() : "?");
1708 } catch (RemoteException e) {
1709 }
Chad Brubakerac925012018-03-08 10:37:09 -08001710 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001711 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001712 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001713 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001714 } finally {
1715 Binder.restoreCallingIdentity(ident);
1716 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001717 }
1718 }
1719
1720 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001721 loadGlobalProxy();
1722
Hugo Benichi20035e02017-04-26 14:53:28 +09001723 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001724 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001725 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001726 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001727 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001728 }
1729 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001730 // load the global proxy at startup
1731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001732
Robin Lee244ce8e2016-01-05 18:03:46 +00001733 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1734 // for user to unlock device too.
1735 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001736
Erik Klineda4bfa82015-04-30 12:58:40 +09001737 // Configure whether mobile data is always on.
1738 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1739
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001741
1742 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001747 *
1748 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001749 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001750 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1752 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001753
1754 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001756
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 if (networkAgent.networkCapabilities.hasTransport(
1758 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001759 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1760 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001761 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001762 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001763 } else if (networkAgent.networkCapabilities.hasTransport(
1764 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001765 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1766 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001767 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001768 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001769 } else {
1770 // do not track any other networks
1771 timeout = 0;
1772 }
1773
Robert Greenwalt7b816022014-04-18 15:25:25 -07001774 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001775 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001776 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001777 } catch (Exception e) {
1778 // You shall not crash!
1779 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001780 }
1781 }
1782 }
1783
1784 /**
1785 * Remove data activity tracking when network disconnects.
1786 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001787 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1788 final String iface = networkAgent.linkProperties.getInterfaceName();
1789 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001790
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1792 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001793 try {
1794 // the call fails silently if no idletimer setup for this interface
1795 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001796 } catch (Exception e) {
1797 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001798 }
1799 }
1800 }
1801
1802 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001803 * Reads the network specific MTU size from reources.
1804 * and set it on it's iface.
1805 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001806 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1807 final String iface = newLp.getInterfaceName();
1808 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001809 if (oldLp == null && mtu == 0) {
1810 // Silently ignore unset MTU value.
1811 return;
1812 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1814 if (VDBG) log("identical MTU - not setting");
1815 return;
1816 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001817 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001818 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001819 return;
1820 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001821
w1997615afd812014-08-05 15:18:11 -07001822 // Cannot set MTU without interface name
1823 if (TextUtils.isEmpty(iface)) {
1824 loge("Setting MTU size with null iface.");
1825 return;
1826 }
1827
Robert Greenwalt7b816022014-04-18 15:25:25 -07001828 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001829 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001830 mNetd.setMtu(iface, mtu);
1831 } catch (Exception e) {
1832 Slog.e(TAG, "exception in setMtu()" + e);
1833 }
1834 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001835
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001836 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001837 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1838
1839 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001840 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001841 protected MockableSystemProperties getSystemProperties() {
1842 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001843 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1846 if (isDefaultNetwork(nai) == false) {
1847 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001848 }
1849
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001850 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1851 String[] values = null;
1852 if (tcpBufferSizes != null) {
1853 values = tcpBufferSizes.split(",");
1854 }
1855
1856 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001857 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001858 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1859 values = tcpBufferSizes.split(",");
1860 }
1861
1862 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1863
1864 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001865 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001866
1867 final String prefix = "/sys/kernel/ipv4/tcp_";
1868 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1869 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1870 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1871 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1872 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1873 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1874 mCurrentTcpBufferSizes = tcpBufferSizes;
1875 } catch (IOException e) {
1876 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001877 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001878
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001879 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001880 Settings.Global.TCP_DEFAULT_INIT_RWND,
1881 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001882 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1883 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001884 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001885 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001886 }
1887
Robert Greenwalt562cc542014-05-15 18:07:26 -07001888 @Override
1889 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001890 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 NETWORK_RESTORE_DELAY_PROP_NAME);
1892 if(restoreDefaultNetworkDelayStr != null &&
1893 restoreDefaultNetworkDelayStr.length() != 0) {
1894 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001895 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 } catch (NumberFormatException e) {
1897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001899 // if the system property isn't set, use the value for the apn type
1900 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1901
1902 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1903 (mNetConfigs[networkType] != null)) {
1904 ret = mNetConfigs[networkType].restoreTime;
1905 }
1906 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001909 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001910 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001911 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001912 }
1913 return false;
1914 }
1915
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001916 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1917 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1918 final long DIAG_TIME_MS = 5000;
1919 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1920 // Start gathering diagnostic information.
1921 netDiags.add(new NetworkDiagnostics(
1922 nai.network,
1923 new LinkProperties(nai.linkProperties), // Must be a copy.
1924 DIAG_TIME_MS));
1925 }
1926
1927 for (NetworkDiagnostics netDiag : netDiags) {
1928 pw.println();
1929 netDiag.waitForMeasurements();
1930 netDiag.dump(pw);
1931 }
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001935 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001936 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1937 }
1938
1939 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001940 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001941 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001942 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001943
Erik Kline7747fd42017-05-12 16:52:48 +09001944 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001945 dumpNetworkDiagnostics(pw);
1946 return;
Erik Klineee363c42017-05-29 09:11:03 +09001947 } else if (argsContain(args, TETHERING_ARG)) {
1948 mTethering.dump(fd, pw, args);
1949 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001950 }
Erik Kline379747a2015-06-05 17:47:34 +09001951
Lorenzo Colittie3805462015-06-03 11:18:24 +09001952 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001953 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001954 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001955 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001956 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001957 pw.println();
1958
Paul Jensen85cf78e2015-06-25 13:25:07 -04001959 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001960 pw.print("Active default network: ");
1961 if (defaultNai == null) {
1962 pw.println("none");
1963 } else {
1964 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001966 pw.println();
1967
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001968 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001969 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001970 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1971 pw.println(nai.toString());
1972 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001973 pw.println(String.format(
1974 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1975 nai.numForegroundNetworkRequests(),
1976 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1977 nai.numBackgroundNetworkRequests(),
1978 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001980 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1981 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001982 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001983 pw.decreaseIndent();
1984 pw.println("Lingered:");
1985 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001986 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001987 pw.decreaseIndent();
1988 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001989 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001990 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001991 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001992
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001994 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1996 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001997 }
1998 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001999 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002000
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002001 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002002
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002003 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002004 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002005
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002006 pw.println();
2007 mKeepaliveTracker.dump(pw);
2008
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002009 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002010 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002011
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002012 pw.println();
2013 mMultipathPolicyTracker.dump(pw);
2014
Erik Kline7747fd42017-05-12 16:52:48 +09002015 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002016 pw.println();
2017 synchronized (mValidationLogs) {
2018 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002019 for (ValidationLog p : mValidationLogs) {
2020 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002021 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002022 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002023 pw.decreaseIndent();
2024 }
2025 }
Erik Kline7523eb32015-07-09 18:24:03 +09002026
2027 pw.println();
2028 pw.println("mNetworkRequestInfoLogs (most recent first):");
2029 pw.increaseIndent();
2030 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2031 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002032
2033 pw.println();
2034 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2035 pw.increaseIndent();
2036 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2037 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002038
2039 pw.println();
2040 pw.println("NetTransition WakeLock activity (most recent first):");
2041 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002042 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2043 pw.println("total releases: " + mTotalWakelockReleases);
2044 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2045 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2046 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2047 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2048 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2049 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002050 mWakelockLogs.reverseDump(fd, pw, args);
2051 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002055 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002056 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002057 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002058 if (officialNai != null && officialNai.equals(nai)) return true;
2059 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002060 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002061 " - " + nai);
2062 }
2063 return false;
2064 }
2065
Robert Greenwalt42acef32009-08-12 16:08:25 -07002066 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002067 private class NetworkStateTrackerHandler extends Handler {
2068 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002069 super(looper);
2070 }
2071
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002072 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002074 default:
2075 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002076 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 handleAsyncChannelHalfConnect(msg);
2078 break;
2079 }
2080 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2081 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2082 if (nai != null) nai.asyncChannel.disconnect();
2083 break;
2084 }
2085 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2086 handleAsyncChannelDisconnected(msg);
2087 break;
2088 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002089 }
2090 return true;
2091 }
2092
2093 private void maybeHandleNetworkAgentMessage(Message msg) {
2094 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2095 if (nai == null) {
2096 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002097 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002098 }
2099 return;
2100 }
2101
2102 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002104 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2105 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002106 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2107 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002109 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002110 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002111 break;
2112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002114 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002115 break;
2116 }
2117 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002118 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 updateNetworkInfo(nai, info);
2120 break;
2121 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002122 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002123 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002124 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002125 break;
2126 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002127 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002128 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2129 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002130 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002131 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002132 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002133 break;
2134 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002135 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002136 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2137 break;
2138 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 }
2140 }
2141
2142 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2143 switch (msg.what) {
2144 default:
2145 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002146 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002147 final NetworkAgentInfo nai;
2148 synchronized (mNetworkForNetId) {
2149 nai = mNetworkForNetId.get(msg.arg2);
2150 }
Erik Klinea24d4592018-01-11 21:07:29 +09002151 if (nai == null) break;
2152
2153 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2154 final boolean wasValidated = nai.lastValidated;
2155 final boolean wasDefault = isDefaultNetwork(nai);
2156
2157 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2158 ? (PrivateDnsConfig) msg.obj : null;
2159 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2160
2161 final boolean reevaluationRequired;
2162 final String logMsg;
2163 if (valid) {
2164 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2165 logMsg = (DBG && (privateDnsCfg != null))
2166 ? " with " + privateDnsCfg.toString() : "";
2167 } else {
2168 reevaluationRequired = false;
2169 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2170 ? " with redirect to " + redirectUrl : "";
2171 }
2172 if (DBG) {
2173 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2174 }
2175 // If there is a change in Private DNS configuration,
2176 // trigger reevaluation of the network to test it.
2177 if (reevaluationRequired) {
2178 nai.networkMonitor.sendMessage(
2179 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2180 break;
2181 }
2182 if (valid != nai.lastValidated) {
2183 if (wasDefault) {
2184 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2185 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002186 }
Erik Klinea24d4592018-01-11 21:07:29 +09002187 final int oldScore = nai.getCurrentScore();
2188 nai.lastValidated = valid;
2189 nai.everValidated |= valid;
2190 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2191 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2192 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2193 }
2194 updateInetCondition(nai);
2195 // Let the NetworkAgent know the state of its network
2196 Bundle redirectUrlBundle = new Bundle();
2197 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2198 nai.asyncChannel.sendMessage(
2199 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2200 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2201 0, redirectUrlBundle);
2202 if (wasValidated && !nai.lastValidated) {
2203 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002204 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 break;
2206 }
Paul Jensen869868be2014-05-15 10:33:05 -04002207 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002208 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002209 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002210 final NetworkAgentInfo nai;
2211 synchronized (mNetworkForNetId) {
2212 nai = mNetworkForNetId.get(netId);
2213 }
Calvin Onbe96da12016-10-11 15:10:46 -07002214 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002215 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002216 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002217 nai.lastCaptivePortalDetected = visible;
2218 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002219 if (nai.lastCaptivePortalDetected &&
2220 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2221 if (DBG) log("Avoiding captive portal network: " + nai.name());
2222 nai.asyncChannel.sendMessage(
2223 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2224 teardownUnneededNetwork(nai);
2225 break;
2226 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002227 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002228 }
2229 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002230 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002231 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002232 if (nai == null) {
2233 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2234 break;
2235 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002236 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002237 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002238 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002239 }
Paul Jensen869868be2014-05-15 10:33:05 -04002240 }
Paul Jensen869868be2014-05-15 10:33:05 -04002241 break;
2242 }
Erik Klinea24d4592018-01-11 21:07:29 +09002243 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2244 final NetworkAgentInfo nai;
2245 synchronized (mNetworkForNetId) {
2246 nai = mNetworkForNetId.get(msg.arg2);
2247 }
2248 if (nai == null) break;
2249
2250 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2251 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2252 if (nai.lastValidated && reevaluationRequired) {
2253 nai.networkMonitor.sendMessage(
2254 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2255 }
2256 break;
2257 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002258 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002259 return true;
2260 }
2261
Calvin Onbe96da12016-10-11 15:10:46 -07002262 private int getCaptivePortalMode() {
2263 return Settings.Global.getInt(mContext.getContentResolver(),
2264 Settings.Global.CAPTIVE_PORTAL_MODE,
2265 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2266 }
2267
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002268 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2269 switch (msg.what) {
2270 default:
2271 return false;
2272 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2273 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2274 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2275 handleLingerComplete(nai);
2276 }
2277 break;
2278 }
2279 }
2280 return true;
2281 }
2282
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002283 @Override
2284 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002285 if (!maybeHandleAsyncChannelMessage(msg) &&
2286 !maybeHandleNetworkMonitorMessage(msg) &&
2287 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002288 maybeHandleNetworkAgentMessage(msg);
2289 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002290 }
2291 }
2292
Erik Klinea24d4592018-01-11 21:07:29 +09002293 private void handlePrivateDnsSettingsChanged() {
2294 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2295
2296 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2297 // Private DNS only ever applies to networks that might provide
2298 // Internet access and therefore also require validation.
2299 if (!NetworkMonitor.isValidationRequired(
2300 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2301 continue;
2302 }
2303
2304 // Notify the NetworkMonitor thread in case it needs to cancel or
2305 // schedule DNS resolutions. If a DNS resolution is required the
2306 // result will be sent back to us.
2307 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2308
2309 if (!cfg.inStrictMode()) {
2310 // No strict mode hostname DNS resolution needed, so just update
2311 // DNS settings directly. In opportunistic and "off" modes this
2312 // just reprograms netd with the network-supplied DNS servers
2313 // (and of course the boolean of whether or not to attempt TLS).
2314 //
2315 // TODO: Consider code flow parity with strict mode, i.e. having
2316 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2317 // performing this call at that time.
2318 updatePrivateDns(nai, cfg);
2319 }
2320 }
2321 }
2322
2323 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2324 final boolean reevaluationRequired = true;
2325 final boolean dontReevaluate = false;
2326
2327 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2328 updateDnses(nai.linkProperties, null, nai.network.netId);
2329
2330 if (newCfg == null) {
2331 if (oldCfg == null) return dontReevaluate;
2332 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2333 }
2334
2335 if (oldCfg == null) {
2336 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2337 }
2338
2339 if (oldCfg.useTls != newCfg.useTls) {
2340 return reevaluationRequired;
2341 }
2342
2343 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2344 return reevaluationRequired;
2345 }
2346
2347 return dontReevaluate;
2348 }
2349
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002350 private void updateLingerState(NetworkAgentInfo nai, long now) {
2351 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2352 // 2. If the network was lingering and there are now requests, unlinger it.
2353 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2354 // one lingered request, start lingering.
2355 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002356 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002357 if (DBG) log("Unlingering " + nai.name());
2358 nai.unlinger();
2359 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002360 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002361 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002362 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002363 nai.linger();
2364 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2365 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2366 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002367 }
2368
Robert Greenwalt7b816022014-04-18 15:25:25 -07002369 private void handleAsyncChannelHalfConnect(Message msg) {
2370 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002371 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2373 if (VDBG) log("NetworkFactory connected");
2374 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002376 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002377 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002378 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002379 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 }
2381 } else {
2382 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002383 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002384 }
2385 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2386 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2387 if (VDBG) log("NetworkAgent connected");
2388 // A network agent has requested a connection. Establish the connection.
2389 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2390 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2391 } else {
2392 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002393 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002394 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002395 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002396 synchronized (mNetworkForNetId) {
2397 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002398 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002399 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002400 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002401 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403 }
2404 }
2405 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002406
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 private void handleAsyncChannelDisconnected(Message msg) {
2408 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2409 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002410 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002411 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002412 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002414 // TODO - if we move the logic to the network agent (have them disconnect
2415 // because they lost all their requests or because their score isn't good)
2416 // then they would disconnect organically, report their new state and then
2417 // disconnect the channel.
2418 if (nai.networkInfo.isConnected()) {
2419 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2420 null, null);
2421 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002422 final boolean wasDefault = isDefaultNetwork(nai);
2423 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002424 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002425 // Log default network disconnection before required book-keeping.
2426 // Let rematchAllNetworksAndRequests() below record a new default network event
2427 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2428 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002429 long now = SystemClock.elapsedRealtime();
2430 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002431 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002432 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002433 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2434 // by other networks that are already connected. Perhaps that can be done by
2435 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2436 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002437 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002438 mKeepaliveTracker.handleStopAllKeepalives(nai,
2439 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002440 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2441 // Disable wakeup packet monitoring for each interface.
2442 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2443 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002444 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002445 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002446 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002447 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002448 // Remove the NetworkAgent, but don't mark the netId as
2449 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002450 mNetworkForNetId.remove(nai.network.netId);
2451 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002452 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002453 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2454 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002455 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002456 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002457 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002458 sendUpdatedScoreToFactories(request, 0);
2459 }
2460 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002461 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002462 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002463 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002464 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002465 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002466 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002467 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002468 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002469 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002470 if (nai.created) {
2471 // Tell netd to clean up the configuration for this network
2472 // (routing rules, DNS, etc).
2473 // This may be slow as it requires a lot of netd shelling out to ip and
2474 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2475 // after we've rematched networks with requests which should make a potential
2476 // fallback network the default or requested a new network from the
2477 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2478 // long time.
2479 try {
2480 mNetd.removeNetwork(nai.network.netId);
2481 } catch (Exception e) {
2482 loge("Exception removing network: " + e);
2483 }
Erik Klinea24d4592018-01-11 21:07:29 +09002484 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002485 }
2486 synchronized (mNetworkForNetId) {
2487 mNetIdInUse.delete(nai.network.netId);
2488 }
2489 } else {
2490 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2491 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002492 }
2493 }
2494
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002495 // If this method proves to be too slow then we can maintain a separate
2496 // pendingIntent => NetworkRequestInfo map.
2497 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2498 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2499 Intent intent = pendingIntent.getIntent();
2500 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2501 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2502 if (existingPendingIntent != null &&
2503 existingPendingIntent.getIntent().filterEquals(intent)) {
2504 return entry.getValue();
2505 }
2506 }
2507 return null;
2508 }
2509
2510 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2511 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2512
2513 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2514 if (existingRequest != null) { // remove the existing request.
2515 if (DBG) log("Replacing " + existingRequest.request + " with "
2516 + nri.request + " because their intents matched.");
2517 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2518 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002519 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002520 }
2521
Erik Klineda4bfa82015-04-30 12:58:40 +09002522 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002523 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002524 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002525 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002526 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002527 if (nri.request.networkCapabilities.hasSignalStrength() &&
2528 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2529 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002530 }
2531 }
2532 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002533 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002534 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002535 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002536 }
2537 }
2538
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002539 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2540 int callingUid) {
2541 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2542 if (nri != null) {
2543 handleReleaseNetworkRequest(nri.request, callingUid);
2544 }
2545 }
2546
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002547 // Determines whether the network is the best (or could become the best, if it validated), for
2548 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2549 // on the value of reason:
2550 //
2551 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2552 // then it should be torn down.
2553 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2554 // then it should be lingered.
2555 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2556 final int numRequests;
2557 switch (reason) {
2558 case TEARDOWN:
2559 numRequests = nai.numRequestNetworkRequests();
2560 break;
2561 case LINGER:
2562 numRequests = nai.numForegroundNetworkRequests();
2563 break;
2564 default:
2565 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2566 return true;
2567 }
2568
2569 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002570 return false;
2571 }
Paul Jensene0988542015-06-25 15:30:08 -04002572 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002573 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2574 // Background requests don't affect lingering.
2575 continue;
2576 }
2577
Paul Jensene0988542015-06-25 15:30:08 -04002578 // If this Network is already the highest scoring Network for a request, or if
2579 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002580 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002581 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002582 // Note that this catches two important cases:
2583 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2584 // is currently satisfying the request. This is desirable when
2585 // cellular ends up validating but WiFi does not.
2586 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002587 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002588 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002589 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002590 nai.getCurrentScoreAsValidated())) {
2591 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002592 }
2593 }
Paul Jensene0988542015-06-25 15:30:08 -04002594 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002595 }
2596
Erik Klineacdd6392016-07-07 16:50:58 +09002597 private NetworkRequestInfo getNriForAppRequest(
2598 NetworkRequest request, int callingUid, String requestedOperation) {
2599 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2600
Robert Greenwalt9258c642014-03-26 16:47:06 -07002601 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002602 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002603 log(String.format("UID %d attempted to %s for unowned request %s",
2604 callingUid, requestedOperation, nri));
2605 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002606 }
Erik Klineacdd6392016-07-07 16:50:58 +09002607 }
2608
2609 return nri;
2610 }
2611
Erik Kline57faba92015-11-25 12:49:38 +09002612 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002613 if (mNetworkRequests.get(nri.request) == null) {
2614 return;
Erik Kline57faba92015-11-25 12:49:38 +09002615 }
Hugo Benichicd952782017-09-20 11:20:14 +09002616 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002617 return;
2618 }
2619 if (VDBG || (DBG && nri.request.isRequest())) {
2620 log("releasing " + nri.request + " (timeout)");
2621 }
2622 handleRemoveNetworkRequest(nri);
2623 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002624 }
2625
Erik Klineacdd6392016-07-07 16:50:58 +09002626 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002627 final NetworkRequestInfo nri =
2628 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2629 if (nri == null) {
2630 return;
Erik Kline57faba92015-11-25 12:49:38 +09002631 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002632 if (VDBG || (DBG && nri.request.isRequest())) {
2633 log("releasing " + nri.request + " (release request)");
2634 }
2635 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002636 }
Erik Klineacdd6392016-07-07 16:50:58 +09002637
Hugo Benichidba33db2017-03-23 22:40:44 +09002638 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002639 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002640 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002641
Erik Klineacdd6392016-07-07 16:50:58 +09002642 synchronized (mUidToNetworkRequestCount) {
2643 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2644 if (requests < 1) {
2645 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2646 nri.mUid);
2647 } else if (requests == 1) {
2648 mUidToNetworkRequestCount.removeAt(
2649 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2650 } else {
2651 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2652 }
2653 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002654
Erik Klineacdd6392016-07-07 16:50:58 +09002655 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2656 if (nri.request.isRequest()) {
2657 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002658 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002659 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002660 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002661 nai.removeRequest(nri.request.requestId);
2662 if (VDBG) {
2663 log(" Removing from current network " + nai.name() +
2664 ", leaving " + nai.numNetworkRequests() + " requests.");
2665 }
2666 // If there are still lingered requests on this network, don't tear it down,
2667 // but resume lingering instead.
2668 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002669 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002670 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2671 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002672 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002673 wasKept = true;
2674 }
Hugo Benichicd952782017-09-20 11:20:14 +09002675 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002676 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2677 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002678 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002679 }
Erik Klineacdd6392016-07-07 16:50:58 +09002680 }
2681
2682 // TODO: remove this code once we know that the Slog.wtf is never hit.
2683 //
2684 // Find all networks that are satisfying this request and remove the request
2685 // from their request lists.
2686 // TODO - it's my understanding that for a request there is only a single
2687 // network satisfying it, so this loop is wasteful
2688 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2689 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2690 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2691 otherNai.name() + ", but mNetworkAgentInfos says " +
2692 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002693 }
2694 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002695
Erik Klineacdd6392016-07-07 16:50:58 +09002696 // Maintain the illusion. When this request arrived, we might have pretended
2697 // that a network connected to serve it, even though the network was already
2698 // connected. Now that this request has gone away, we might have to pretend
2699 // that the network disconnected. LegacyTypeTracker will generate that
2700 // phantom disconnect for this type.
2701 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2702 boolean doRemove = true;
2703 if (wasKept) {
2704 // check if any of the remaining requests for this network are for the
2705 // same legacy type - if so, don't remove the nai
2706 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2707 NetworkRequest otherRequest = nai.requestAt(i);
2708 if (otherRequest.legacyType == nri.request.legacyType &&
2709 otherRequest.isRequest()) {
2710 if (DBG) log(" still have other legacy request - leaving");
2711 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002712 }
2713 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002714 }
2715
Erik Klineacdd6392016-07-07 16:50:58 +09002716 if (doRemove) {
2717 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002718 }
2719 }
Erik Klineacdd6392016-07-07 16:50:58 +09002720
2721 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2722 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2723 nri.request);
2724 }
2725 } else {
2726 // listens don't have a singular affectedNetwork. Check all networks to see
2727 // if this listen request applies and remove it.
2728 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2729 nai.removeRequest(nri.request.requestId);
2730 if (nri.request.networkCapabilities.hasSignalStrength() &&
2731 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2732 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2733 }
2734 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002735 }
2736 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002737
Lorenzo Colitti18660282016-07-04 12:55:44 +09002738 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2740 enforceConnectivityInternalPermission();
2741 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002742 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002743 }
2744
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002745 @Override
2746 public void setAvoidUnvalidated(Network network) {
2747 enforceConnectivityInternalPermission();
2748 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2749 }
2750
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002751 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2752 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2753 " accept=" + accept + " always=" + always);
2754
2755 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2756 if (nai == null) {
2757 // Nothing to do.
2758 return;
2759 }
2760
2761 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002762 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002763 return;
2764 }
2765
2766 if (!nai.networkMisc.explicitlySelected) {
2767 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2768 }
2769
2770 if (accept != nai.networkMisc.acceptUnvalidated) {
2771 int oldScore = nai.getCurrentScore();
2772 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002773 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002774 sendUpdatedScoreToFactories(nai);
2775 }
2776
2777 if (always) {
2778 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002779 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002780 }
2781
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002782 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002783 // Tell the NetworkAgent to not automatically reconnect to the network.
2784 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2785 // Teardown the nework.
2786 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002787 }
2788
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002789 }
2790
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002791 private void handleSetAvoidUnvalidated(Network network) {
2792 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2793 if (nai == null || nai.lastValidated) {
2794 // Nothing to do. The network either disconnected or revalidated.
2795 return;
2796 }
2797 if (!nai.avoidUnvalidated) {
2798 int oldScore = nai.getCurrentScore();
2799 nai.avoidUnvalidated = true;
2800 rematchAllNetworksAndRequests(nai, oldScore);
2801 sendUpdatedScoreToFactories(nai);
2802 }
2803 }
2804
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002805 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002806 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002807 mHandler.sendMessageDelayed(
2808 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2809 PROMPT_UNVALIDATED_DELAY_MS);
2810 }
2811
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002812 @Override
2813 public void startCaptivePortalApp(Network network) {
2814 enforceConnectivityInternalPermission();
2815 mHandler.post(() -> {
2816 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2817 if (nai == null) return;
2818 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2819 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2820 });
2821 }
2822
Hugo Benichic8e9e122016-09-14 23:23:08 +00002823 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002824 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002825 }
2826
Erik Kline065ab6e2016-10-02 18:02:14 +09002827 private void rematchForAvoidBadWifiUpdate() {
2828 rematchAllNetworksAndRequests(null, 0);
2829 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2830 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2831 sendUpdatedScoreToFactories(nai);
2832 }
2833 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002834 }
2835
Erik Kline065ab6e2016-10-02 18:02:14 +09002836 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002837 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002838 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002839 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002840 if (!configRestrict) {
2841 pw.println("Bad Wi-Fi avoidance: unrestricted");
2842 return;
2843 }
2844
2845 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2846 pw.increaseIndent();
2847 pw.println("Config restrict: " + configRestrict);
2848
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002849 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002850 String description;
2851 // Can't use a switch statement because strings are legal case labels, but null is not.
2852 if ("0".equals(value)) {
2853 description = "get stuck";
2854 } else if (value == null) {
2855 description = "prompt";
2856 } else if ("1".equals(value)) {
2857 description = "avoid";
2858 } else {
2859 description = value + " (?)";
2860 }
2861 pw.println("User setting: " + description);
2862 pw.println("Network overrides:");
2863 pw.increaseIndent();
2864 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2865 if (nai.avoidUnvalidated) {
2866 pw.println(nai.name());
2867 }
2868 }
2869 pw.decreaseIndent();
2870 pw.decreaseIndent();
2871 }
2872
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002873 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2874 final String action;
2875 switch (type) {
2876 case NO_INTERNET:
2877 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2878 break;
2879 case LOST_INTERNET:
2880 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2881 break;
2882 default:
2883 Slog.wtf(TAG, "Unknown notification type " + type);
2884 return;
2885 }
2886
2887 Intent intent = new Intent(action);
2888 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2889 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2890 intent.setClassName("com.android.settings",
2891 "com.android.settings.wifi.WifiNoInternetDialog");
2892
2893 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2894 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2895 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2896 }
2897
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002898 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002899 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002900 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2901
2902 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2903 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002904 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002905 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002906 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2907 return;
2908 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002909 showValidationNotification(nai, NotificationType.NO_INTERNET);
2910 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002911
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002912 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2913 NetworkCapabilities nc = nai.networkCapabilities;
2914 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002915
Erik Kline065ab6e2016-10-02 18:02:14 +09002916 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002917 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002918 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2919 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002920 }
2921
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002922 @Override
2923 public int getMultipathPreference(Network network) {
2924 enforceAccessPermission();
2925
2926 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002927 if (nai != null && nai.networkCapabilities
2928 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002929 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2930 }
2931
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002932 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2933 if (networkPreference != null) {
2934 return networkPreference;
2935 }
2936
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002937 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2938 }
2939
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002940 private class InternalHandler extends Handler {
2941 public InternalHandler(Looper looper) {
2942 super(looper);
2943 }
2944
2945 @Override
2946 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002947 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002948 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002949 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002950 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002951 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002952 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002953 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002955 break;
2956 }
Jason Monkdecd2952013-10-10 14:02:51 -04002957 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002958 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002959 break;
2960 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002961 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002962 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2963 break;
2964 }
2965 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2966 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002967 break;
2968 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002969 case EVENT_REGISTER_NETWORK_AGENT: {
2970 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2971 break;
2972 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002973 case EVENT_REGISTER_NETWORK_REQUEST:
2974 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002975 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002976 break;
2977 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002978 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2979 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002980 handleRegisterNetworkRequestWithIntent(msg);
2981 break;
2982 }
Erik Kline57faba92015-11-25 12:49:38 +09002983 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2984 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2985 handleTimedOutNetworkRequest(nri);
2986 break;
2987 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002988 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2989 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2990 break;
2991 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002992 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002993 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002994 break;
2995 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002996 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002997 Network network = (Network) msg.obj;
2998 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002999 break;
3000 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003001 case EVENT_SET_AVOID_UNVALIDATED: {
3002 handleSetAvoidUnvalidated((Network) msg.obj);
3003 break;
3004 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003005 case EVENT_PROMPT_UNVALIDATED: {
3006 handlePromptUnvalidated((Network) msg.obj);
3007 break;
3008 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003009 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3010 handleMobileDataAlwaysOn();
3011 break;
3012 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003013 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3014 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3015 mKeepaliveTracker.handleStartKeepalive(msg);
3016 break;
3017 }
3018 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3019 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3020 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3021 int slot = msg.arg1;
3022 int reason = msg.arg2;
3023 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3024 break;
3025 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003026 case EVENT_SYSTEM_READY: {
3027 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3028 nai.networkMonitor.systemReady = true;
3029 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003030 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003031 break;
3032 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003033 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003034 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003035 break;
3036 }
Erik Klinea24d4592018-01-11 21:07:29 +09003037 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3038 handlePrivateDnsSettingsChanged();
3039 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 }
3041 }
3042 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003043
3044 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003045 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003046 public int tether(String iface, String callerPkg) {
3047 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003048 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003049 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003050 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003051 } else {
3052 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3053 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003054 }
3055
3056 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003057 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003058 public int untether(String iface, String callerPkg) {
3059 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003060
3061 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003062 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003063 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003064 } else {
3065 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3066 }
3067 }
3068
3069 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003070 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003071 public int getLastTetherError(String iface) {
3072 enforceTetherAccessPermission();
3073
3074 if (isTetheringSupported()) {
3075 return mTethering.getLastTetherError(iface);
3076 } else {
3077 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3078 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003079 }
3080
3081 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003082 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003083 public String[] getTetherableUsbRegexs() {
3084 enforceTetherAccessPermission();
3085 if (isTetheringSupported()) {
3086 return mTethering.getTetherableUsbRegexs();
3087 } else {
3088 return new String[0];
3089 }
3090 }
3091
Lorenzo Colitti18660282016-07-04 12:55:44 +09003092 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003093 public String[] getTetherableWifiRegexs() {
3094 enforceTetherAccessPermission();
3095 if (isTetheringSupported()) {
3096 return mTethering.getTetherableWifiRegexs();
3097 } else {
3098 return new String[0];
3099 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003100 }
3101
Lorenzo Colitti18660282016-07-04 12:55:44 +09003102 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003103 public String[] getTetherableBluetoothRegexs() {
3104 enforceTetherAccessPermission();
3105 if (isTetheringSupported()) {
3106 return mTethering.getTetherableBluetoothRegexs();
3107 } else {
3108 return new String[0];
3109 }
3110 }
3111
Lorenzo Colitti18660282016-07-04 12:55:44 +09003112 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003113 public int setUsbTethering(boolean enable, String callerPkg) {
3114 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003115 if (isTetheringSupported()) {
3116 return mTethering.setUsbTethering(enable);
3117 } else {
3118 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3119 }
3120 }
3121
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003122 // TODO - move iface listing, queries, etc to new module
3123 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003124 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003125 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003126 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003127 return mTethering.getTetherableIfaces();
3128 }
3129
Lorenzo Colitti18660282016-07-04 12:55:44 +09003130 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003131 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003132 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003133 return mTethering.getTetheredIfaces();
3134 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003135
Lorenzo Colitti18660282016-07-04 12:55:44 +09003136 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003137 public String[] getTetheringErroredIfaces() {
3138 enforceTetherAccessPermission();
3139 return mTethering.getErroredIfaces();
3140 }
3141
Lorenzo Colitti18660282016-07-04 12:55:44 +09003142 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003143 public String[] getTetheredDhcpRanges() {
3144 enforceConnectivityInternalPermission();
3145 return mTethering.getTetheredDhcpRanges();
3146 }
3147
Udam Saini0e94c362017-06-07 12:06:28 -07003148 @Override
3149 public boolean isTetheringSupported(String callerPkg) {
3150 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3151 return isTetheringSupported();
3152 }
3153
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003154 // if ro.tether.denied = true we default to no tethering
3155 // gservices could set the secure setting to 1 though to enable it on a build where it
3156 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003157 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003158 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3159 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3160 Settings.Global.TETHER_SUPPORTED, defaultVal));
3161 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003162 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003163
3164 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3165 boolean adminUser = false;
3166 final long token = Binder.clearCallingIdentity();
3167 try {
3168 adminUser = mUserManager.isAdminUser();
3169 } finally {
3170 Binder.restoreCallingIdentity(token);
3171 }
3172
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003173 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003174 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003175
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003176 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003177 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3178 String callerPkg) {
3179 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003180 if (!isTetheringSupported()) {
3181 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3182 return;
3183 }
3184 mTethering.startTethering(type, receiver, showProvisioningUi);
3185 }
3186
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003187 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003188 public void stopTethering(int type, String callerPkg) {
3189 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003190 mTethering.stopTethering(type);
3191 }
3192
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003193 // Called when we lose the default network and have no replacement yet.
3194 // This will automatically be cleared after X seconds or a new default network
3195 // becomes CONNECTED, whichever happens first. The timer is started by the
3196 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003197 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003198 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003199 if (mNetTransitionWakeLock.isHeld()) {
3200 return;
3201 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003202 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003203 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3204 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003205 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003206 mWakelockLogs.log("ACQUIRE for " + forWhom);
3207 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3208 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003209 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003210
Hugo Benichi4c31b342017-03-30 23:18:10 +09003211 // Called when we gain a new default network to release the network transition wakelock in a
3212 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3213 // message is cancelled.
3214 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003215 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003216 if (!mNetTransitionWakeLock.isHeld()) {
3217 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003218 }
3219 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003220 // Cancel self timeout on wakelock hold.
3221 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3222 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3223 mHandler.sendMessageDelayed(msg, 1000);
3224 }
3225
3226 // Called when either message of ensureNetworkTransitionWakelock or
3227 // scheduleReleaseNetworkTransitionWakelock is processed.
3228 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3229 String event = eventName(eventId);
3230 synchronized (this) {
3231 if (!mNetTransitionWakeLock.isHeld()) {
3232 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3233 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3234 return;
3235 }
3236 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003237 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3238 mTotalWakelockDurationMs += lockDuration;
3239 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3240 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003241 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003242 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003243 }
3244
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003245 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003246 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003247 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003248 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003249 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003250 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003251 }
3252
Lorenzo Colitti18660282016-07-04 12:55:44 +09003253 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003254 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003255 enforceAccessPermission();
3256 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003257 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003258 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003259 mHandler.sendMessage(
3260 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3261 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003262
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003263 private void handleReportNetworkConnectivity(
3264 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003265 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003266 if (network == null) {
3267 nai = getDefaultNetwork();
3268 } else {
3269 nai = getNetworkAgentInfoForNetwork(network);
3270 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003271 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3272 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3273 return;
3274 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003275 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003276 if (hasConnectivity == nai.lastValidated) {
3277 return;
3278 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003279 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003280 int netid = nai.network.netId;
3281 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003282 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003283 // Validating a network that has not yet connected could result in a call to
3284 // rematchNetworkAndRequests() which is not meant to work on such networks.
3285 if (!nai.everConnected) {
3286 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003287 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003288 LinkProperties lp = getLinkProperties(nai);
3289 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3290 return;
3291 }
3292 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003293 }
3294
Paul Jensencee9b512015-05-06 07:32:40 -04003295 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003296 // this information is already available as a world read/writable jvm property
3297 // so this API change wouldn't have a benifit. It also breaks the passing
3298 // of proxy info to all the JVMs.
3299 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003300 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003301 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003302 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3303 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003304 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305 }
3306
Lorenzo Colitti18660282016-07-04 12:55:44 +09003307 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003308 public ProxyInfo getProxyForNetwork(Network network) {
3309 if (network == null) return getDefaultProxy();
3310 final ProxyInfo globalProxy = getGlobalProxy();
3311 if (globalProxy != null) return globalProxy;
3312 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3313 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3314 // caller may not have.
3315 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3316 if (nai == null) return null;
3317 synchronized (nai) {
3318 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3319 if (proxyInfo == null) return null;
3320 return new ProxyInfo(proxyInfo);
3321 }
3322 }
3323
Paul Jensene0bef712014-12-10 15:12:18 -05003324 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3325 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3326 // proxy is null then there is no proxy in place).
3327 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3328 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3329 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3330 proxy = null;
3331 }
3332 return proxy;
3333 }
3334
3335 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3336 // better for determining if a new proxy broadcast is necessary:
3337 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3338 // avoid unnecessary broadcasts.
3339 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3340 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3341 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3342 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3343 // all set.
3344 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3345 a = canonicalizeProxyInfo(a);
3346 b = canonicalizeProxyInfo(b);
3347 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3348 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3349 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3350 }
3351
Jason Monk207900c2014-04-25 15:00:09 -04003352 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003353 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003354
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003355 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 if (proxyProperties == mGlobalProxy) return;
3357 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3358 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3359
3360 String host = "";
3361 int port = 0;
3362 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003363 String pacFileUrl = "";
3364 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003365 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003366 if (!proxyProperties.isValid()) {
3367 if (DBG)
3368 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3369 return;
3370 }
Jason Monk207900c2014-04-25 15:00:09 -04003371 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003372 host = mGlobalProxy.getHost();
3373 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003374 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003375 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003376 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003377 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 } else {
3379 mGlobalProxy = null;
3380 }
3381 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003382 final long token = Binder.clearCallingIdentity();
3383 try {
3384 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3385 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3386 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3387 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003388 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003389 } finally {
3390 Binder.restoreCallingIdentity(token);
3391 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392
Jason Monkcf0f97a2014-10-02 15:39:38 -04003393 if (mGlobalProxy == null) {
3394 proxyProperties = mDefaultProxy;
3395 }
3396 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003397 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003398 }
3399
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003400 private void loadGlobalProxy() {
3401 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003402 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3403 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3404 String exclList = Settings.Global.getString(res,
3405 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003406 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3407 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003408 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003409 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003410 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003411 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003412 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003413 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003414 if (!proxyProperties.isValid()) {
3415 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3416 return;
3417 }
3418
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003419 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003420 mGlobalProxy = proxyProperties;
3421 }
3422 }
3423 }
3424
Jason Monk207900c2014-04-25 15:00:09 -04003425 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003426 // this information is already available as a world read/writable jvm property
3427 // so this API change wouldn't have a benifit. It also breaks the passing
3428 // of proxy info to all the JVMs.
3429 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003430 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003431 return mGlobalProxy;
3432 }
3433 }
3434
Jason Monk207900c2014-04-25 15:00:09 -04003435 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003436 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003437 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003438 proxy = null;
3439 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003440 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003441 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003442 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003443 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003444 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3445 return;
3446 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003447
3448 // This call could be coming from the PacManager, containing the port of the local
3449 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3450 // global (to get the correct local port), and send a broadcast.
3451 // TODO: Switch PacManager to have its own message to send back rather than
3452 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003453 if ((mGlobalProxy != null) && (proxy != null)
3454 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003455 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3456 mGlobalProxy = proxy;
3457 sendProxyBroadcast(mGlobalProxy);
3458 return;
3459 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003460 mDefaultProxy = proxy;
3461
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003462 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003463 if (!mDefaultProxyDisabled) {
3464 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 }
3466 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003467 }
3468
Paul Jensene0bef712014-12-10 15:12:18 -05003469 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3470 // This method gets called when any network changes proxy, but the broadcast only ever contains
3471 // the default proxy (even if it hasn't changed).
3472 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3473 // world where an app might be bound to a non-default network.
3474 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3475 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3476 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3477
3478 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3479 sendProxyBroadcast(getDefaultProxy());
3480 }
3481 }
3482
Robert Greenwalt434203a2010-10-11 16:00:27 -07003483 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003484 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3485 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003486 if (!TextUtils.isEmpty(proxy)) {
3487 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003488 if (data.length == 0) {
3489 return;
3490 }
3491
Robert Greenwalt434203a2010-10-11 16:00:27 -07003492 String proxyHost = data[0];
3493 int proxyPort = 8080;
3494 if (data.length > 1) {
3495 try {
3496 proxyPort = Integer.parseInt(data[1]);
3497 } catch (NumberFormatException e) {
3498 return;
3499 }
3500 }
Jason Monk207900c2014-04-25 15:00:09 -04003501 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003502 setGlobalProxy(p);
3503 }
3504 }
3505
Jason Monk207900c2014-04-25 15:00:09 -04003506 private void sendProxyBroadcast(ProxyInfo proxy) {
3507 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003508 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003509 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003510 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003511 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3512 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003513 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003514 final long ident = Binder.clearCallingIdentity();
3515 try {
3516 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3517 } finally {
3518 Binder.restoreCallingIdentity(ident);
3519 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003520 }
3521
3522 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003523 final private HashMap<Uri, Integer> mUriEventMap;
3524 final private Context mContext;
3525 final private Handler mHandler;
3526
3527 SettingsObserver(Context context, Handler handler) {
3528 super(null);
3529 mUriEventMap = new HashMap<Uri, Integer>();
3530 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003532 }
3533
Erik Klineda4bfa82015-04-30 12:58:40 +09003534 void observe(Uri uri, int what) {
3535 mUriEventMap.put(uri, what);
3536 final ContentResolver resolver = mContext.getContentResolver();
3537 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003538 }
3539
3540 @Override
3541 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003542 Slog.wtf(TAG, "Should never be reached.");
3543 }
3544
3545 @Override
3546 public void onChange(boolean selfChange, Uri uri) {
3547 final Integer what = mUriEventMap.get(uri);
3548 if (what != null) {
3549 mHandler.obtainMessage(what.intValue()).sendToTarget();
3550 } else {
3551 loge("No matching event to send for URI=" + uri);
3552 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003553 }
3554 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003555
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003556 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003557 Slog.d(TAG, s);
3558 }
3559
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003560 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003561 Slog.e(TAG, s);
3562 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003563
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003564 private static void loge(String s, Throwable t) {
3565 Slog.e(TAG, s, t);
3566 }
3567
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003568 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003569 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003570 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3571 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3572 *
3573 * @param oldPackage Package name of the application which currently controls VPN, which will
3574 * be replaced. If there is no such application, this should should either be
3575 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3576 * @param newPackage Package name of the application which should gain control of VPN, or
3577 * {@code null} to disable.
3578 * @param userId User for whom to prepare the new VPN.
3579 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003580 * @hide
3581 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003582 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003583 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3584 int userId) {
3585 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003586
Hugo Benichi20035e02017-04-26 14:53:28 +09003587 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003588 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003589 Vpn vpn = mVpns.get(userId);
3590 if (vpn != null) {
3591 return vpn.prepare(oldPackage, newPackage);
3592 } else {
3593 return false;
3594 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003595 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003596 }
3597
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003598 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003599 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3600 * This method is used by system-privileged apps.
3601 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3602 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3603 *
3604 * @param packageName The package for which authorization state should change.
3605 * @param userId User for whom {@code packageName} is installed.
3606 * @param authorized {@code true} if this app should be able to start a VPN connection without
3607 * explicit user approval, {@code false} if not.
3608 *
Jeff Davidson05542602014-08-11 14:07:27 -07003609 * @hide
3610 */
3611 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003612 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3613 enforceCrossUserPermission(userId);
3614
Hugo Benichi20035e02017-04-26 14:53:28 +09003615 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003616 Vpn vpn = mVpns.get(userId);
3617 if (vpn != null) {
3618 vpn.setPackageAuthorization(packageName, authorized);
3619 }
Jeff Davidson05542602014-08-11 14:07:27 -07003620 }
3621 }
3622
3623 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003624 * Configure a TUN interface and return its file descriptor. Parameters
3625 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003626 * and not available in ConnectivityManager. Permissions are checked in
3627 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003628 * @hide
3629 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003630 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003631 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003632 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003633 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003634 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003635 return mVpns.get(user).establish(config);
3636 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003637 }
3638
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003639 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003640 * Start legacy VPN, controlling native daemons as needed. Creates a
3641 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003642 */
3643 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003644 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003645 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003646 final LinkProperties egress = getActiveLinkProperties();
3647 if (egress == null) {
3648 throw new IllegalStateException("Missing active network connection");
3649 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003650 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003651 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003652 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3653 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003654 }
3655
3656 /**
3657 * Return the information of the ongoing legacy VPN. This method is used
3658 * by VpnSettings and not available in ConnectivityManager. Permissions
3659 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003660 */
3661 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003662 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3663 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003664
Hugo Benichi20035e02017-04-26 14:53:28 +09003665 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003666 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003667 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003668 }
3669
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003670 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003671 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3672 * and not available in ConnectivityManager.
3673 */
3674 @Override
3675 public VpnInfo[] getAllVpnInfo() {
3676 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003677 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003678 if (mLockdownEnabled) {
3679 return new VpnInfo[0];
3680 }
3681
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003682 List<VpnInfo> infoList = new ArrayList<>();
3683 for (int i = 0; i < mVpns.size(); i++) {
3684 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3685 if (info != null) {
3686 infoList.add(info);
3687 }
3688 }
3689 return infoList.toArray(new VpnInfo[infoList.size()]);
3690 }
3691 }
3692
3693 /**
3694 * @return VPN information for accounting, or null if we can't retrieve all required
3695 * information, e.g primary underlying iface.
3696 */
3697 @Nullable
3698 private VpnInfo createVpnInfo(Vpn vpn) {
3699 VpnInfo info = vpn.getVpnInfo();
3700 if (info == null) {
3701 return null;
3702 }
3703 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3704 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3705 // the underlyingNetworks list.
3706 if (underlyingNetworks == null) {
3707 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3708 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3709 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3710 }
3711 } else if (underlyingNetworks.length > 0) {
3712 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3713 if (linkProperties != null) {
3714 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3715 }
3716 }
3717 return info.primaryUnderlyingIface == null ? null : info;
3718 }
3719
3720 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003721 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3722 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003723 * Permissions are checked in Vpn class.
3724 * @hide
3725 */
3726 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003727 public VpnConfig getVpnConfig(int userId) {
3728 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003729 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003730 Vpn vpn = mVpns.get(userId);
3731 if (vpn != null) {
3732 return vpn.getVpnConfig();
3733 } else {
3734 return null;
3735 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003736 }
3737 }
3738
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003739 @Override
3740 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003741 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3742 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3743 return false;
3744 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003745
Hugo Benichi69744342017-11-27 10:57:16 +09003746 synchronized (mVpns) {
3747 // Tear down existing lockdown if profile was removed
3748 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3749 if (mLockdownEnabled) {
3750 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3751 if (profileTag == null) {
3752 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3753 return false;
3754 }
3755 String profileName = new String(profileTag);
3756 final VpnProfile profile = VpnProfile.decode(
3757 profileName, mKeyStore.get(Credentials.VPN + profileName));
3758 if (profile == null) {
3759 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3760 setLockdownTracker(null);
3761 return true;
3762 }
3763 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003764 Vpn vpn = mVpns.get(user);
3765 if (vpn == null) {
3766 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3767 return false;
3768 }
3769 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003770 } else {
3771 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003772 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003773 }
3774
3775 return true;
3776 }
3777
3778 /**
3779 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3780 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3781 */
Hugo Benichi69744342017-11-27 10:57:16 +09003782 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003783 private void setLockdownTracker(LockdownVpnTracker tracker) {
3784 // Shutdown any existing tracker
3785 final LockdownVpnTracker existing = mLockdownTracker;
3786 mLockdownTracker = null;
3787 if (existing != null) {
3788 existing.shutdown();
3789 }
3790
Robin Leec3736bc2017-03-10 16:19:54 +00003791 if (tracker != null) {
3792 mLockdownTracker = tracker;
3793 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003794 }
3795 }
3796
Hugo Benichi69744342017-11-27 10:57:16 +09003797 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003798 private void throwIfLockdownEnabled() {
3799 if (mLockdownEnabled) {
3800 throw new IllegalStateException("Unavailable in lockdown mode");
3801 }
3802 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003803
Robin Lee244ce8e2016-01-05 18:03:46 +00003804 /**
Robin Lee17e61832016-05-09 13:46:28 +01003805 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3806 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003807 *
Robin Lee17e61832016-05-09 13:46:28 +01003808 * @return {@code true} if the service was started, the service was already connected, or there
3809 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003810 */
Robin Lee17e61832016-05-09 13:46:28 +01003811 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003812 synchronized (mVpns) {
3813 Vpn vpn = mVpns.get(userId);
3814 if (vpn == null) {
3815 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3816 // exists already.
3817 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3818 return false;
3819 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003820
Robin Lee812800c2016-05-13 15:38:08 +01003821 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003822 }
3823 }
3824
3825 @Override
Charles He36738632017-05-15 17:07:18 +01003826 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3827 enforceSettingsPermission();
3828 enforceCrossUserPermission(userId);
3829
3830 synchronized (mVpns) {
3831 Vpn vpn = mVpns.get(userId);
3832 if (vpn == null) {
3833 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3834 return false;
3835 }
3836 return vpn.isAlwaysOnPackageSupported(packageName);
3837 }
3838 }
3839
3840 @Override
Robin Leedc679712016-05-03 13:23:03 +01003841 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003842 enforceConnectivityInternalPermission();
3843 enforceCrossUserPermission(userId);
3844
Robin Lee244ce8e2016-01-05 18:03:46 +00003845 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003846 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3847 if (LockdownVpnTracker.isEnabled()) {
3848 return false;
3849 }
3850
Robin Lee244ce8e2016-01-05 18:03:46 +00003851 Vpn vpn = mVpns.get(userId);
3852 if (vpn == null) {
3853 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3854 return false;
3855 }
Robin Lee17e61832016-05-09 13:46:28 +01003856 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003857 return false;
3858 }
Robin Lee17e61832016-05-09 13:46:28 +01003859 if (!startAlwaysOnVpn(userId)) {
3860 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003861 return false;
3862 }
3863 }
3864 return true;
3865 }
3866
3867 @Override
3868 public String getAlwaysOnVpnPackage(int userId) {
3869 enforceConnectivityInternalPermission();
3870 enforceCrossUserPermission(userId);
3871
3872 synchronized (mVpns) {
3873 Vpn vpn = mVpns.get(userId);
3874 if (vpn == null) {
3875 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3876 return null;
3877 }
3878 return vpn.getAlwaysOnPackage();
3879 }
3880 }
3881
Wink Savilleab9321d2013-06-29 21:10:57 -07003882 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003883 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003884 // TODO: Remove? Any reason to trigger a provisioning check?
3885 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003886 }
3887
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003888 /** Location to an updatable file listing carrier provisioning urls.
3889 * An example:
3890 *
3891 * <?xml version="1.0" encoding="utf-8"?>
3892 * <provisioningUrls>
3893 * <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 -07003894 * </provisioningUrls>
3895 */
3896 private static final String PROVISIONING_URL_PATH =
3897 "/data/misc/radio/provisioning_urls.xml";
3898 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003899
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003900 /** XML tag for root element. */
3901 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3902 /** XML tag for individual url */
3903 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003904 /** XML attribute for mcc */
3905 private static final String ATTR_MCC = "mcc";
3906 /** XML attribute for mnc */
3907 private static final String ATTR_MNC = "mnc";
3908
Paul Jensen434dde82015-06-11 09:43:30 -04003909 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003910 FileReader fileReader = null;
3911 XmlPullParser parser = null;
3912 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003913
3914 try {
3915 fileReader = new FileReader(mProvisioningUrlFile);
3916 parser = Xml.newPullParser();
3917 parser.setInput(fileReader);
3918 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3919
3920 while (true) {
3921 XmlUtils.nextElement(parser);
3922
3923 String element = parser.getName();
3924 if (element == null) break;
3925
Paul Jensen434dde82015-06-11 09:43:30 -04003926 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003927 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3928 try {
3929 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3930 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3931 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3932 parser.next();
3933 if (parser.getEventType() == XmlPullParser.TEXT) {
3934 return parser.getText();
3935 }
3936 }
3937 }
3938 } catch (NumberFormatException e) {
3939 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3940 }
3941 }
3942 }
3943 return null;
3944 } catch (FileNotFoundException e) {
3945 loge("Carrier Provisioning Urls file not found");
3946 } catch (XmlPullParserException e) {
3947 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3948 } catch (IOException e) {
3949 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3950 } finally {
3951 if (fileReader != null) {
3952 try {
3953 fileReader.close();
3954 } catch (IOException e) {}
3955 }
3956 }
3957 return null;
3958 }
3959
Wink Saville42d4f082013-07-20 20:31:59 -07003960 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003961 public String getMobileProvisioningUrl() {
3962 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003963 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003964 if (TextUtils.isEmpty(url)) {
3965 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003966 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003967 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003968 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003969 }
Wink Saville8cf35602013-07-10 23:00:07 -07003970 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003971 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003972 String phoneNumber = mTelephonyManager.getLine1Number();
3973 if (TextUtils.isEmpty(phoneNumber)) {
3974 phoneNumber = "0000000000";
3975 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003976 url = String.format(url,
3977 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3978 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003979 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003980 }
3981
Wink Savilleab9321d2013-06-29 21:10:57 -07003982 return url;
3983 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003984
Wink Saville948282b2013-08-29 08:55:16 -07003985 @Override
3986 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003987 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003988 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003989 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3990 return;
3991 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003992 final long ident = Binder.clearCallingIdentity();
3993 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003994 // Concatenate the range of types onto the range of NetIDs.
3995 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3996 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003997 } finally {
3998 Binder.restoreCallingIdentity(ident);
3999 }
Wink Saville948282b2013-08-29 08:55:16 -07004000 }
Wink Saville7788c612013-08-29 14:57:08 -07004001
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004002 @Override
4003 public void setAirplaneMode(boolean enable) {
4004 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004005 final long ident = Binder.clearCallingIdentity();
4006 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004007 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004008 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004009 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4010 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004011 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004012 } finally {
4013 Binder.restoreCallingIdentity(ident);
4014 }
4015 }
4016
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004017 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004018 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004019 Vpn userVpn = mVpns.get(userId);
4020 if (userVpn != null) {
4021 loge("Starting user already has a VPN");
4022 return;
4023 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004024 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004025 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004026 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4027 updateLockdownVpn();
4028 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004029 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004030 }
4031
4032 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004033 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004034 Vpn userVpn = mVpns.get(userId);
4035 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004036 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004037 return;
4038 }
Robin Lee17e61832016-05-09 13:46:28 +01004039 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004040 mVpns.delete(userId);
4041 }
4042 }
4043
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004044 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004045 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004046 final int vpnsSize = mVpns.size();
4047 for (int i = 0; i < vpnsSize; i++) {
4048 Vpn vpn = mVpns.valueAt(i);
4049 vpn.onUserAdded(userId);
4050 }
4051 }
4052 }
4053
4054 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004055 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004056 final int vpnsSize = mVpns.size();
4057 for (int i = 0; i < vpnsSize; i++) {
4058 Vpn vpn = mVpns.valueAt(i);
4059 vpn.onUserRemoved(userId);
4060 }
4061 }
4062 }
4063
Robin Lee89e7a692016-02-29 14:38:17 +00004064 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004065 synchronized (mVpns) {
4066 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4067 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4068 updateLockdownVpn();
4069 } else {
4070 startAlwaysOnVpn(userId);
4071 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004072 }
4073 }
4074
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004075 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4076 @Override
4077 public void onReceive(Context context, Intent intent) {
4078 final String action = intent.getAction();
4079 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4080 if (userId == UserHandle.USER_NULL) return;
4081
Robin Lee323f29d2016-05-04 16:38:06 +01004082 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004083 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004084 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004085 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004086 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4087 onUserAdded(userId);
4088 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4089 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004090 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4091 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004092 }
4093 }
4094 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004095
Robin Lee95204e02017-01-27 11:59:22 +00004096 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4097 @Override
4098 public void onReceive(Context context, Intent intent) {
4099 // Try creating lockdown tracker, since user present usually means
4100 // unlocked keystore.
4101 updateLockdownVpn();
4102 mContext.unregisterReceiver(this);
4103 }
4104 };
4105
Robert Greenwalta67be032014-05-16 15:49:14 -07004106 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4107 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4109 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004110
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004111 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4112 // Map from UID to number of NetworkRequests that UID has filed.
4113 @GuardedBy("mUidToNetworkRequestCount")
4114 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4115
Robert Greenwalta67be032014-05-16 15:49:14 -07004116 private static class NetworkFactoryInfo {
4117 public final String name;
4118 public final Messenger messenger;
4119 public final AsyncChannel asyncChannel;
4120
4121 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4122 this.name = name;
4123 this.messenger = messenger;
4124 this.asyncChannel = asyncChannel;
4125 }
4126 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004127
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004128 private void ensureNetworkRequestHasType(NetworkRequest request) {
4129 if (request.type == NetworkRequest.Type.NONE) {
4130 throw new IllegalArgumentException(
4131 "All NetworkRequests in ConnectivityService must have a type");
4132 }
4133 }
4134
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004135 /**
4136 * Tracks info about the requester.
4137 * Also used to notice when the calling process dies so we can self-expire
4138 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004141 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004142 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004143 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 final int mPid;
4145 final int mUid;
4146 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004148 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004150 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004151 mPendingIntent = pi;
4152 messenger = null;
4153 mBinder = null;
4154 mPid = getCallingPid();
4155 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004156 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004157 }
4158
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004159 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160 super();
4161 messenger = m;
4162 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004163 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 mBinder = binder;
4165 mPid = getCallingPid();
4166 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004168 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169
4170 try {
4171 mBinder.linkToDeath(this, 0);
4172 } catch (RemoteException e) {
4173 binderDied();
4174 }
4175 }
4176
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004177 private void enforceRequestCountLimit() {
4178 synchronized (mUidToNetworkRequestCount) {
4179 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4180 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004181 throw new ServiceSpecificException(
4182 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004183 }
4184 mUidToNetworkRequestCount.put(mUid, networkRequests);
4185 }
4186 }
4187
Robert Greenwalt9258c642014-03-26 16:47:06 -07004188 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 if (mBinder != null) {
4190 mBinder.unlinkToDeath(this, 0);
4191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 }
4193
4194 public void binderDied() {
4195 log("ConnectivityService NetworkRequestInfo binderDied(" +
4196 request + ", " + mBinder + ")");
4197 releaseNetworkRequest(request);
4198 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004199
4200 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004201 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004202 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004204 }
4205
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004206 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4207 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4208 if (badCapability != null) {
4209 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004210 }
4211 }
4212
Erik Kline9d598e12015-07-13 16:37:51 +09004213 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004214 final SortedSet<Integer> thresholds = new TreeSet();
4215 synchronized (nai) {
4216 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4217 if (nri.request.networkCapabilities.hasSignalStrength() &&
4218 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4219 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4220 }
4221 }
4222 }
Erik Kline9d598e12015-07-13 16:37:51 +09004223 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004224 }
4225
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004226 private void updateSignalStrengthThresholds(
4227 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4228 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004229 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004230 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4231
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004232 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004233 String detail;
4234 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4235 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4236 } else {
4237 detail = reason;
4238 }
4239 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4240 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4241 }
4242
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004243 nai.asyncChannel.sendMessage(
4244 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004245 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004246 }
4247
Etan Cohen859748f2017-04-03 17:42:34 -07004248 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4249 if (nc == null) {
4250 return;
4251 }
4252 NetworkSpecifier ns = nc.getNetworkSpecifier();
4253 if (ns == null) {
4254 return;
4255 }
4256 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4257 ns.assertValidFromUid(Binder.getCallingUid());
4258 }
4259
Robert Greenwalt9258c642014-03-26 16:47:06 -07004260 @Override
4261 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004262 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004263 final NetworkRequest.Type type = (networkCapabilities == null)
4264 ? NetworkRequest.Type.TRACK_DEFAULT
4265 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004266 // If the requested networkCapabilities is null, take them instead from
4267 // the default network request. This allows callers to keep track of
4268 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004269 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004270 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004271 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004272 enforceAccessPermission();
4273 } else {
4274 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4275 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004276 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4277 // of the app when the request is filed, but we never change the request if the app
4278 // changes network state. http://b/29964605
4279 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004280 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004281 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004282 // Set the UID range for this request to the single UID of the requester, or to an empty
4283 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004284 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4285 // are no visible methods to set the UIDs, an app could use reflection to try and get
4286 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004287 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004288
Etan Cohenba07c8c2017-02-05 10:42:27 -08004289 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004290 throw new IllegalArgumentException("Bad timeout specified");
4291 }
Etan Cohen859748f2017-04-03 17:42:34 -07004292 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004293
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004294 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004295 nextNetworkRequestId(), type);
4296 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004297 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298
4299 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004300 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004302 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004303 }
4304 return networkRequest;
4305 }
4306
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004307 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004308 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004309 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004310 } else {
4311 enforceChangePermission();
4312 }
4313 }
4314
fenglub15e72b2015-03-20 11:29:56 -07004315 @Override
fengludb571472015-04-21 17:12:05 -07004316 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004317 enforceAccessPermission();
4318 NetworkAgentInfo nai = null;
4319 if (network == null) {
4320 return false;
4321 }
4322 synchronized (mNetworkForNetId) {
4323 nai = mNetworkForNetId.get(network.netId);
4324 }
4325 if (nai != null) {
4326 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4327 return true;
4328 }
4329 return false;
4330 }
4331
Felipe Lemeee27cab2016-06-20 16:36:29 -07004332 private boolean isSystem(int uid) {
4333 return uid < Process.FIRST_APPLICATION_UID;
4334 }
fenglub15e72b2015-03-20 11:29:56 -07004335
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004336 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004337 final int uid = Binder.getCallingUid();
4338 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004339 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004340 return;
4341 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004342 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4343 // Policy already enforced.
4344 return;
4345 }
4346 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4347 // If UID is restricted, don't allow them to bring up metered APNs.
4348 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004349 }
4350 }
4351
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 @Override
4353 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4354 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004355 checkNotNull(operation, "PendingIntent cannot be null.");
4356 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4357 enforceNetworkRequestPermissions(networkCapabilities);
4358 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004359 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004360 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004361 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004362
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004363 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004364 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4365 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004366 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004367 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4368 nri));
4369 return networkRequest;
4370 }
4371
Jeremy Joslin79294842014-12-03 17:15:28 -08004372 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4373 mHandler.sendMessageDelayed(
4374 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4375 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4376 }
4377
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004378 @Override
4379 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004380 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004381 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4382 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 }
4384
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004385 // In order to implement the compatibility measure for pre-M apps that call
4386 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4387 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4388 // This ensures it has permission to do so.
4389 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4390 if (nc == null) {
4391 return false;
4392 }
4393 int[] transportTypes = nc.getTransportTypes();
4394 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4395 return false;
4396 }
4397 try {
4398 mContext.enforceCallingOrSelfPermission(
4399 android.Manifest.permission.ACCESS_WIFI_STATE,
4400 "ConnectivityService");
4401 } catch (SecurityException e) {
4402 return false;
4403 }
4404 return true;
4405 }
4406
Robert Greenwalt9258c642014-03-26 16:47:06 -07004407 @Override
4408 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4409 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004410 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4411 enforceAccessPermission();
4412 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004413
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004414 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004415 restrictRequestUidsForCaller(nc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004416 if (!ConnectivityManager.checkChangePermission(mContext)) {
4417 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4418 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4419 // onLost and onAvailable callbacks when networks move in and out of the background.
4420 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4421 // can't request networks.
4422 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4423 }
Etan Cohen859748f2017-04-03 17:42:34 -07004424 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004425
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004426 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004427 NetworkRequest.Type.LISTEN);
4428 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004429 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004430
4431 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4432 return networkRequest;
4433 }
4434
4435 @Override
4436 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4437 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004438 checkNotNull(operation, "PendingIntent cannot be null.");
4439 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4440 enforceAccessPermission();
4441 }
Etan Cohen859748f2017-04-03 17:42:34 -07004442 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004443
Chalard Jeandda156a2018-01-10 21:19:32 +09004444 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004445 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004446
4447 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004448 NetworkRequest.Type.LISTEN);
4449 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004450 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004451
4452 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004453 }
4454
Erik Klineacdd6392016-07-07 16:50:58 +09004455 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004456 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004457 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004458 mHandler.sendMessage(mHandler.obtainMessage(
4459 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004460 }
4461
4462 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004463 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004464 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004465 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4466 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004467 }
4468
Robert Greenwalta67be032014-05-16 15:49:14 -07004469 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004470 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004471 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4472 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4473 }
4474
4475 @Override
4476 public void unregisterNetworkFactory(Messenger messenger) {
4477 enforceConnectivityInternalPermission();
4478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4479 }
4480
4481 private void handleUnregisterNetworkFactory(Messenger messenger) {
4482 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4483 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004484 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004485 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004486 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004487 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004488 }
4489
Robert Greenwalt7b816022014-04-18 15:25:25 -07004490 /**
4491 * NetworkAgentInfo supporting a request by requestId.
4492 * These have already been vetted (their Capabilities satisfy the request)
4493 * and the are the highest scored network available.
4494 * the are keyed off the Requests requestId.
4495 */
Hugo Benichicd952782017-09-20 11:20:14 +09004496 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4497 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4499 new SparseArray<NetworkAgentInfo>();
4500
Paul Jensen31a94f42015-02-13 14:18:39 -05004501 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4502 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004503 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4504 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004505 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4506 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4507 // there may not be a strict 1:1 correlation between the two.
4508 @GuardedBy("mNetworkForNetId")
4509 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004510
Robert Greenwalt7b816022014-04-18 15:25:25 -07004511 // NetworkAgentInfo keyed off its connecting messenger
4512 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004513 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004514 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4515 new HashMap<Messenger, NetworkAgentInfo>();
4516
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004517 @GuardedBy("mBlockedAppUids")
4518 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4519
Paul Jensen2c311d62014-11-17 12:34:51 -05004520 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 private final NetworkRequest mDefaultRequest;
4522
Erik Klineda4bfa82015-04-30 12:58:40 +09004523 // Request used to optionally keep mobile data active even when higher
4524 // priority networks like Wi-Fi are active.
4525 private final NetworkRequest mDefaultMobileDataRequest;
4526
Hugo Benichicd952782017-09-20 11:20:14 +09004527 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4528 synchronized (mNetworkForRequestId) {
4529 return mNetworkForRequestId.get(requestId);
4530 }
4531 }
4532
4533 private void clearNetworkForRequest(int requestId) {
4534 synchronized (mNetworkForRequestId) {
4535 mNetworkForRequestId.remove(requestId);
4536 }
4537 }
4538
4539 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4540 synchronized (mNetworkForRequestId) {
4541 mNetworkForRequestId.put(requestId, nai);
4542 }
4543 }
4544
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004545 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004546 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004547 }
4548
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004549 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004550 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004551 }
4552
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004553 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4554 return nri.request.requestId == mDefaultRequest.requestId;
4555 }
4556
Paul Jensen31a94f42015-02-13 14:18:39 -05004557 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004559 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 enforceConnectivityInternalPermission();
4561
Rubin Xu1bb5c082017-09-05 18:40:49 +01004562 LinkProperties lp = new LinkProperties(linkProperties);
4563 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004564 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4565 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004566 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004567 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004568 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004569 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004570 // Make sure the network capabilities reflect what the agent info says.
4571 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004572 synchronized (this) {
4573 nai.networkMonitor.systemReady = mSystemReady;
4574 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004575 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4576 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004577 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004579 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 }
4581
4582 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4583 if (VDBG) log("Got NetworkAgent Messenger");
4584 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004585 synchronized (mNetworkForNetId) {
4586 mNetworkForNetId.put(na.network.netId, na);
4587 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004588 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4589 NetworkInfo networkInfo = na.networkInfo;
4590 na.networkInfo = null;
4591 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004592 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 }
4594
4595 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4596 LinkProperties newLp = networkAgent.linkProperties;
4597 int netId = networkAgent.network.netId;
4598
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004599 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4600 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004601 if (networkAgent.clatd != null) {
4602 networkAgent.clatd.fixupLinkProperties(oldLp);
4603 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004604
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004605 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 updateMtu(newLp, oldLp);
4607 // TODO - figure out what to do for clat
4608// for (LinkProperties lp : newLp.getStackedLinks()) {
4609// updateMtu(lp, null);
4610// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004611 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004612
Erik Kline94887872016-04-05 13:30:49 +09004613 updateRoutes(newLp, oldLp, netId);
4614 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004615
Hugo Benichi6f62b732017-06-27 15:13:20 +09004616 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004617 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004618 if (isDefaultNetwork(networkAgent)) {
4619 handleApplyDefaultProxy(newLp.getHttpProxy());
4620 } else {
4621 updateProxy(newLp, oldLp, networkAgent);
4622 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004623 // TODO - move this check to cover the whole function
4624 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004625 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004626 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4627 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004628
4629 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004630 }
4631
Joel Scherpelz668370b2017-06-08 15:35:21 +09004632 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004633 // Marks are only available on WiFi interaces. Checking for
4634 // marks on unsupported interfaces is harmless.
4635 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4636 return;
4637 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004638
Joel Scherpelz668370b2017-06-08 15:35:21 +09004639 int mark = mContext.getResources().getInteger(
4640 com.android.internal.R.integer.config_networkWakeupPacketMark);
4641 int mask = mContext.getResources().getInteger(
4642 com.android.internal.R.integer.config_networkWakeupPacketMask);
4643
4644 // Mask/mark of zero will not detect anything interesting.
4645 // Don't install rules unless both values are nonzero.
4646 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004647 return;
4648 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004649
4650 final String prefix = "iface:" + iface;
4651 try {
4652 if (add) {
4653 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4654 } else {
4655 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4656 }
4657 } catch (Exception e) {
4658 loge("Exception modifying wakeup packet monitoring: " + e);
4659 }
4660
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004661 }
4662
4663 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4664 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004665 CompareResult<String> interfaceDiff = new CompareResult<String>(
4666 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4667 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004668 for (String iface : interfaceDiff.added) {
4669 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004670 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004671 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004672 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004673 } catch (Exception e) {
4674 loge("Exception adding interface: " + e);
4675 }
4676 }
4677 for (String iface : interfaceDiff.removed) {
4678 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004679 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004680 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004681 mNetd.removeInterfaceFromNetwork(iface, netId);
4682 } catch (Exception e) {
4683 loge("Exception removing interface: " + e);
4684 }
4685 }
4686 }
4687
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004688 /**
4689 * Have netd update routes from oldLp to newLp.
4690 * @return true if routes changed between oldLp and newLp
4691 */
4692 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004693 // Compare the route diff to determine which routes should be added and removed.
4694 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4695 oldLp != null ? oldLp.getAllRoutes() : null,
4696 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697
4698 // add routes before removing old in case it helps with continuous connectivity
4699
4700 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4701 for (RouteInfo route : routeDiff.added) {
4702 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004703 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004704 try {
4705 mNetd.addRoute(netId, route);
4706 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004707 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4708 loge("Exception in addRoute for non-gateway: " + e);
4709 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004710 }
4711 }
4712 for (RouteInfo route : routeDiff.added) {
4713 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004714 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004715 try {
4716 mNetd.addRoute(netId, route);
4717 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004718 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4719 loge("Exception in addRoute for gateway: " + e);
4720 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004721 }
4722 }
4723
4724 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004725 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004726 try {
4727 mNetd.removeRoute(netId, route);
4728 } catch (Exception e) {
4729 loge("Exception in removeRoute: " + e);
4730 }
4731 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004732 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004733 }
Erik Kline41368502015-06-17 13:19:54 +09004734
Erik Kline94887872016-04-05 13:30:49 +09004735 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4736 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4737 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 }
Erik Kline94887872016-04-05 13:30:49 +09004739
Erik Kline1742fe12017-12-13 19:40:49 +09004740 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4741 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4742
Erik Klinea24d4592018-01-11 21:07:29 +09004743 if (DBG) {
4744 final Collection<InetAddress> dnses = newLp.getDnsServers();
4745 log("Setting DNS servers for network " + netId + " to " + dnses);
4746 }
Erik Kline94887872016-04-05 13:30:49 +09004747 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004748 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004749 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004750 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004751 }
Erik Kline4edba012017-04-07 15:29:29 +09004752 }
4753
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004754 private String getNetworkPermission(NetworkCapabilities nc) {
4755 // TODO: make these permission strings AIDL constants instead.
4756 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4757 return NetworkManagementService.PERMISSION_SYSTEM;
4758 }
4759 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4760 return NetworkManagementService.PERMISSION_NETWORK;
4761 }
4762 return null;
4763 }
4764
Paul Jensen3d194ea2015-06-16 14:27:36 -04004765 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004766 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4767 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4768 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004769 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004770 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004771 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004772 if (nai.everConnected &&
4773 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4774 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004775 // does not cause any request (that is not a listen) currently matching that agent to
4776 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004777 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004778 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004779 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004780 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004781 }
4782
Paul Jensen3d194ea2015-06-16 14:27:36 -04004783 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004784 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004785 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004786 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004787 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004788 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004789 }
Paul Jensene0988542015-06-25 15:30:08 -04004790 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004791 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004792 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004793 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004794 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004795 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004796 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004797 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004798 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004799 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004800 if (nai.isSuspended()) {
4801 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4802 } else {
4803 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4804 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004805
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004806 return newNc;
4807 }
4808
4809 /**
4810 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4811 *
4812 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4813 * capabilities we manage and store in {@code nai}, such as validated status and captive
4814 * portal status)
4815 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4816 * potentially triggers rematches.
4817 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4818 * change.)
4819 *
4820 * @param oldScore score of the network before any of the changes that prompted us
4821 * to call this function.
4822 * @param nai the network having its capabilities updated.
4823 * @param nc the new network capabilities.
4824 */
4825 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4826 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4827
4828 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004829
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004830 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004831 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004832 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004833 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004834 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004835 } catch (RemoteException e) {
4836 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004837 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004838 }
4839
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004840 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004841 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004842 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004843 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004844 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004845
Chalard Jeanf213ca12018-01-16 18:43:05 +09004846 updateUids(nai, prevNc, newNc);
4847
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004848 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004849 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4850 // the change we're processing can't affect any requests, it can only affect the listens
4851 // on this network. We might have been called by rematchNetworkAndRequests when a
4852 // network changed foreground state.
4853 processListenRequests(nai, true);
4854 } else {
4855 // If the requestable capabilities have changed or the score changed, we can't have been
4856 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004857 rematchAllNetworksAndRequests(nai, oldScore);
4858 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004859 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004860
4861 // Report changes that are interesting for network statistics tracking.
4862 if (prevNc != null) {
4863 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004864 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004865 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004866 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004867 if (meteredChanged || roamingChanged) {
4868 notifyIfacesChangedForNetworkStats();
4869 }
4870 }
4871
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004872 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004873 // Tell VPNs about updated capabilities, since they may need to
4874 // bubble those changes through.
4875 synchronized (mVpns) {
4876 for (int i = 0; i < mVpns.size(); i++) {
4877 final Vpn vpn = mVpns.valueAt(i);
4878 vpn.updateCapabilities();
4879 }
4880 }
4881 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004882 }
4883
Chalard Jeanf213ca12018-01-16 18:43:05 +09004884 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4885 NetworkCapabilities newNc) {
4886 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4887 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4888 if (null == prevRanges) prevRanges = new ArraySet<>();
4889 if (null == newRanges) newRanges = new ArraySet<>();
4890 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4891
4892 prevRanges.removeAll(newRanges);
4893 newRanges.removeAll(prevRangesCopy);
4894
4895 try {
4896 if (!newRanges.isEmpty()) {
4897 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4898 newRanges.toArray(addedRangesArray);
4899 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4900 }
4901 if (!prevRanges.isEmpty()) {
4902 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4903 prevRanges.toArray(removedRangesArray);
4904 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4905 }
4906 } catch (Exception e) {
4907 // Never crash!
4908 loge("Exception in updateUids: " + e);
4909 }
4910 }
4911
Hugo Benichief502882017-09-01 01:23:32 +00004912 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4913 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4914 // Ignore updates for disconnected networks
4915 return;
4916 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004917 // newLp is already a defensive copy.
4918 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004919 if (VDBG) {
4920 log("Update of LinkProperties for " + nai.name() +
4921 "; created=" + nai.created +
4922 "; everConnected=" + nai.everConnected);
4923 }
4924 LinkProperties oldLp = nai.linkProperties;
4925 synchronized (nai) {
4926 nai.linkProperties = newLp;
4927 }
4928 if (nai.everConnected) {
4929 updateLinkProperties(nai, oldLp);
4930 }
4931 }
4932
Paul Jensenc8b9a742014-09-30 15:37:41 -04004933 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004934 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4935 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004936 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004937 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004938 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4939 }
4940 }
4941
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4943 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004944 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004945 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4946 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004947 }
4948 }
4949
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004950 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4951 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004952 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004953 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004954 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4955 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004956 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004957 sendIntent(nri.mPendingIntent, intent);
4958 }
4959 // else not handled
4960 }
4961
4962 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4963 mPendingIntentWakeLock.acquire();
4964 try {
4965 if (DBG) log("Sending " + pendingIntent);
4966 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4967 } catch (PendingIntent.CanceledException e) {
4968 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4969 mPendingIntentWakeLock.release();
4970 releasePendingNetworkRequest(pendingIntent);
4971 }
4972 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4973 }
4974
4975 @Override
4976 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4977 String resultData, Bundle resultExtras) {
4978 if (DBG) log("Finished sending " + pendingIntent);
4979 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004980 // Release with a delay so the receiving client has an opportunity to put in its
4981 // own request.
4982 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004983 }
4984
Chalard Jeanf19db372018-01-26 19:24:40 +09004985 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004986 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004987 if (nri.messenger == null) {
4988 return; // Default request has no msgr
4989 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004990 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004991 // TODO: check if defensive copies of data is needed.
4992 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004993 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004994 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4995 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004996 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004997 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004998 case ConnectivityManager.CALLBACK_AVAILABLE: {
4999 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5000 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5001 break;
5002 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005003 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005004 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005005 break;
5006 }
5007 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005008 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09005009 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
5010 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005011 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005012 break;
5013 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005014 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005015 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005016 break;
5017 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005018 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005019 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005020 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005021 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005022 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005023 String notification = ConnectivityManager.getCallbackName(notificationType);
5024 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005025 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005026 nri.messenger.send(msg);
5027 } catch (RemoteException e) {
5028 // may occur naturally in the race of binder death.
5029 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5030 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005031 }
5032
Hugo Benichidba33db2017-03-23 22:40:44 +09005033 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5034 bundle.putParcelable(t.getClass().getSimpleName(), t);
5035 }
5036
Paul Jensenc8b9a742014-09-30 15:37:41 -04005037 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005038 if (nai.numRequestNetworkRequests() != 0) {
5039 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5040 NetworkRequest nr = nai.requestAt(i);
5041 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005042 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005043 loge("Dead network still had at least " + nr);
5044 break;
5045 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005046 }
5047 nai.asyncChannel.disconnect();
5048 }
5049
Robert Greenwalt7b816022014-04-18 15:25:25 -07005050 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5051 if (oldNetwork == null) {
5052 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5053 return;
5054 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005055 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005056
5057 // If we get here it means that the last linger timeout for this network expired. So there
5058 // must be no other active linger timers, and we must stop lingering.
5059 oldNetwork.clearLingerState();
5060
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005061 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005062 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005063 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005064 } else {
5065 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005066 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5067 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005069 }
5070
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005071 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005072 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005073 setupDataActivityTracking(newNetwork);
5074 try {
5075 mNetd.setDefaultNetId(newNetwork.network.netId);
5076 } catch (Exception e) {
5077 loge("Exception setting default network :" + e);
5078 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005079
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005080 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005081 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005082 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005083 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005084 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005085 }
5086
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005087 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005088 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5089 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5090 NetworkRequest nr = nri.request;
5091 if (!nr.isListen()) continue;
5092 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5093 nai.removeRequest(nri.request.requestId);
5094 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5095 }
5096 }
5097
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005098 if (capabilitiesChanged) {
5099 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5100 }
5101
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005102 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5103 NetworkRequest nr = nri.request;
5104 if (!nr.isListen()) continue;
5105 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5106 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005107 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005108 }
5109 }
5110 }
5111
Paul Jensen2161a8e2014-09-11 11:00:39 -04005112 // Handles a network appearing or improving its score.
5113 //
5114 // - Evaluates all current NetworkRequests that can be
5115 // satisfied by newNetwork, and reassigns to newNetwork
5116 // any such requests for which newNetwork is the best.
5117 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005118 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005119 // needed. A network is needed if it is the best network for
5120 // one or more NetworkRequests, or if it is a VPN.
5121 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005122 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005123 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005124 //
5125 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5126 // networks that have no chance (i.e. even if validated)
5127 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005128 //
5129 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5130 // it does not remove NetworkRequests that other Networks could better satisfy.
5131 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5132 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5133 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005134 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005135 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005136 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5137 // performed to tear down unvalidated networks that have no chance (i.e. even if
5138 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005139 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005140 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005141 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005142 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005144 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005145
5146 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5147 final int score = newNetwork.getCurrentScore();
5148
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005149 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005150
Paul Jensen2161a8e2014-09-11 11:00:39 -04005151 // Find and migrate to this Network any NetworkRequests for
5152 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005153 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005154 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005155 NetworkCapabilities nc = newNetwork.networkCapabilities;
5156 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005157 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005158 // Process requests in the first pass and listens in the second pass. This allows us to
5159 // change a network's capabilities depending on which requests it has. This is only
5160 // correct if the change in capabilities doesn't affect whether the network satisfies
5161 // requests or not, and doesn't affect the network's score.
5162 if (nri.request.isListen()) continue;
5163
Hugo Benichicd952782017-09-20 11:20:14 +09005164 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005165 final boolean satisfies = newNetwork.satisfies(nri.request);
5166 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005167 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005168 log("Network " + newNetwork.name() + " was already satisfying" +
5169 " request " + nri.request.requestId + ". No change.");
5170 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005171 keep = true;
5172 continue;
5173 }
5174
5175 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005176 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005177 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005178 // next check if it's better than any current network we're using for
5179 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005180 if (VDBG) {
5181 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005182 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005183 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005184 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005185 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005186 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005188 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005189 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005190 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005191 affectedNetworks.add(currentNetwork);
5192 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005193 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005194 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005195 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005196 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005197 if (!newNetwork.addRequest(nri.request)) {
5198 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5199 }
5200 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005202 // Tell NetworkFactories about the new score, so they can stop
5203 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005204 // TODO - this could get expensive if we have alot of requests for this
5205 // network. Think about if there is a way to reduce this. Push
5206 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005207 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005208 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005209 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005210 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005211 if (currentNetwork != null) {
5212 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5213 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005214 }
5215 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005216 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005217 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5218 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005219 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005220 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5221 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5222 // This means this code doesn't have to handle the case where "currentNetwork" no
5223 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5224 if (DBG) {
5225 log("Network " + newNetwork.name() + " stopped satisfying" +
5226 " request " + nri.request.requestId);
5227 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005228 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005229 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005230 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005231 sendUpdatedScoreToFactories(nri.request, 0);
5232 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005233 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5234 newNetwork.name() +
5235 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005236 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005237 // TODO: Technically, sending CALLBACK_LOST here is
5238 // incorrect if there is a replacement network currently
5239 // connected that can satisfy nri, which is a request
5240 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005241 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5242 // so this code is only incorrect for a network that loses
5243 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005244 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005245 }
5246 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005247 if (isNewDefault) {
5248 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005249 makeDefault(newNetwork);
5250 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005251 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005252 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005253 // Have a new default network, release the transition wakelock in
5254 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005255 }
5256
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005257 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5258 Slog.wtf(TAG, String.format(
5259 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005260 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005261 }
5262 if (newNetwork.getCurrentScore() != score) {
5263 Slog.wtf(TAG, String.format(
5264 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005265 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005266 }
5267
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005268 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005269 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5270 // If the network went from background to foreground or vice versa, we need to update
5271 // its foreground state. It is safe to do this after rematching the requests because
5272 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5273 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005274 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005275 } else {
5276 processListenRequests(newNetwork, false);
5277 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005278
Paul Jensencf4c2c62015-07-01 14:16:32 -04005279 // do this after the default net is switched, but
5280 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005281 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005282
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005283 // Linger any networks that are no longer needed. This should be done after sending the
5284 // available callback for newNetwork.
5285 for (NetworkAgentInfo nai : affectedNetworks) {
5286 updateLingerState(nai, now);
5287 }
5288 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5289 // does not need to be done in any particular order.
5290 updateLingerState(newNetwork, now);
5291
Paul Jensencf4c2c62015-07-01 14:16:32 -04005292 if (isNewDefault) {
5293 // Maintain the illusion: since the legacy API only
5294 // understands one network at a time, we must pretend
5295 // that the current default network disconnected before
5296 // the new one connected.
5297 if (oldDefaultNetwork != null) {
5298 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5299 oldDefaultNetwork, true);
5300 }
5301 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5302 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5303 notifyLockdownVpn(newNetwork);
5304 }
5305
Robert Greenwalt7b816022014-04-18 15:25:25 -07005306 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005307 // Notify battery stats service about this network, both the normal
5308 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005309 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005310 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005311 final IBatteryStats bs = BatteryStatsService.getService();
5312 final int type = newNetwork.networkInfo.getType();
5313
5314 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5315 bs.noteNetworkInterfaceType(baseIface, type);
5316 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5317 final String stackedIface = stacked.getInterfaceName();
5318 bs.noteNetworkInterfaceType(stackedIface, type);
5319 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5320 }
5321 } catch (RemoteException ignored) {
5322 }
5323
Robert Greenwalt152ed372014-12-17 17:19:53 -08005324 // This has to happen after the notifyNetworkCallbacks as that tickles each
5325 // ConnectivityManager instance so that legacy requests correctly bind dns
5326 // requests to this network. The legacy users are listening for this bcast
5327 // and will generally do a dns request so they can ensureRouteToHost and if
5328 // they do that before the callbacks happen they'll use the default network.
5329 //
5330 // TODO: Is there still a race here? We send the broadcast
5331 // after sending the callback, but if the app can receive the
5332 // broadcast before the callback, it might still break.
5333 //
5334 // This *does* introduce a race where if the user uses the new api
5335 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5336 // they may get old info. Reverse this after the old startUsing api is removed.
5337 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005338 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5339 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005340 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005341 // legacy type tracker filters out repeat adds
5342 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5343 }
5344 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005345
5346 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5347 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5348 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5349 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5350 if (newNetwork.isVPN()) {
5351 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5352 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005353 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005354 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5355 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005356 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005357 if (nai.getLingerExpiry() > 0) {
5358 // This network has active linger timers and no requests, but is not
5359 // lingering. Linger it.
5360 //
5361 // One way (the only way?) this can happen if this network is unvalidated
5362 // and became unneeded due to another network improving its score to the
5363 // point where this network will no longer be able to satisfy any requests
5364 // even if it validates.
5365 updateLingerState(nai, now);
5366 } else {
5367 if (DBG) log("Reaping " + nai.name());
5368 teardownUnneededNetwork(nai);
5369 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005370 }
5371 }
5372 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005373 }
5374
Paul Jensen1c7ba022015-06-16 14:27:36 -04005375 /**
5376 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5377 * being disconnected.
5378 * @param changed If only one Network's score or capabilities have been modified since the last
5379 * time this function was called, pass this Network in this argument, otherwise pass
5380 * null.
5381 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5382 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5383 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5384 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5385 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005386 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005387 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005388 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5389 // to avoid the slowness. It is not simply enough to process just "changed", for
5390 // example in the case where "changed"'s score decreases and another network should begin
5391 // satifying a NetworkRequest that "changed" currently satisfies.
5392
5393 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5394 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5395 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005396 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005397 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005398 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005399 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005400 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5401 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5402 // Rematch higher scoring networks first to prevent requests first matching a lower
5403 // scoring network and then a higher scoring network, which could produce multiple
5404 // callbacks and inadvertently unlinger networks.
5405 Arrays.sort(nais);
5406 for (NetworkAgentInfo nai : nais) {
5407 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005408 // Only reap the last time through the loop. Reaping before all rematching
5409 // is complete could incorrectly teardown a network that hasn't yet been
5410 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005411 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005412 : ReapUnvalidatedNetworks.REAP,
5413 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005414 }
5415 }
5416 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005417
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005418 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005419 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005420 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005421 // For now only update icons for default connection.
5422 // TODO: Update WiFi and cellular icons separately. b/17237507
5423 if (!isDefaultNetwork(nai)) return;
5424
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005425 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005426 // Don't repeat publish.
5427 if (newInetCondition == mDefaultInetConditionPublished) return;
5428
5429 mDefaultInetConditionPublished = newInetCondition;
5430 sendInetConditionBroadcast(nai.networkInfo);
5431 }
5432
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005433 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005434 synchronized (mVpns) {
5435 if (mLockdownTracker != null) {
5436 if (nai != null && nai.isVPN()) {
5437 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5438 } else {
5439 mLockdownTracker.onNetworkInfoChanged();
5440 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005441 }
5442 }
5443 }
5444
Robert Greenwalt7b816022014-04-18 15:25:25 -07005445 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005446 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005447 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005448 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005449 synchronized (networkAgent) {
5450 oldInfo = networkAgent.networkInfo;
5451 networkAgent.networkInfo = newInfo;
5452 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005453 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005454
Robert Greenwalt7b816022014-04-18 15:25:25 -07005455 if (DBG) {
5456 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5457 (oldInfo == null ? "null" : oldInfo.getState()) +
5458 " to " + state);
5459 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005460
Robin Lee585e2482016-05-01 23:00:00 +01005461 if (!networkAgent.created
5462 && (state == NetworkInfo.State.CONNECTED
5463 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005464
5465 // A network that has just connected has zero requests and is thus a foreground network.
5466 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5467
Robert Greenwalt7b816022014-04-18 15:25:25 -07005468 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005469 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005470 if (networkAgent.isVPN()) {
5471 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005472 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5473 (networkAgent.networkMisc == null ||
5474 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005475 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005476 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005477 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005478 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005479 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005480 loge("Error creating network " + networkAgent.network.netId + ": "
5481 + e.getMessage());
5482 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005483 }
Paul Jenseneec75412014-08-04 12:21:19 -04005484 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005485 }
5486
5487 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5488 networkAgent.everConnected = true;
5489
Robert Greenwalt7b816022014-04-18 15:25:25 -07005490 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005491 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005492
Paul Jensenca8f16a2014-05-09 12:47:55 -04005493 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005494 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005495
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005496 if (networkAgent.isVPN()) {
5497 // Temporarily disable the default proxy (not global).
5498 synchronized (mProxyLock) {
5499 if (!mDefaultProxyDisabled) {
5500 mDefaultProxyDisabled = true;
5501 if (mGlobalProxy == null && mDefaultProxy != null) {
5502 sendProxyBroadcast(null);
5503 }
5504 }
5505 }
5506 // TODO: support proxy per network.
5507 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005508
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005509 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5510 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5511 // capabilities, so it only needs to be done once on initial connect, not every time the
5512 // network's capabilities change. Note that we do this before rematching the network,
5513 // so we could decide to tear it down immediately afterwards. That's fine though - on
5514 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5515 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005516 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005517
Paul Jensen2161a8e2014-09-11 11:00:39 -04005518 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005519 final long now = SystemClock.elapsedRealtime();
5520 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005521
5522 // This has to happen after matching the requests, because callbacks are just requests.
5523 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005524 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005525 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005526 if (networkAgent.isVPN()) {
5527 synchronized (mProxyLock) {
5528 if (mDefaultProxyDisabled) {
5529 mDefaultProxyDisabled = false;
5530 if (mGlobalProxy == null && mDefaultProxy != null) {
5531 sendProxyBroadcast(mDefaultProxy);
5532 }
5533 }
5534 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005535 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005536 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005537 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5538 state == NetworkInfo.State.SUSPENDED) {
5539 // going into or coming out of SUSPEND: rescore and notify
5540 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005541 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005542 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005543 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5544 networkAgent.networkCapabilities);
5545 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5546 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005547 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5548 ConnectivityManager.CALLBACK_SUSPENDED :
5549 ConnectivityManager.CALLBACK_RESUMED));
5550 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005551 }
5552 }
5553
Robert Greenwaltac96c522014-06-03 16:43:57 -07005554 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005555 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005556 if (score < 0) {
5557 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5558 "). Bumping score to min of 0");
5559 score = 0;
5560 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005561
Paul Jensen2161a8e2014-09-11 11:00:39 -04005562 final int oldScore = nai.getCurrentScore();
5563 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005564
Paul Jensen85cf78e2015-06-25 13:25:07 -04005565 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005566
Paul Jensenc8b9a742014-09-30 15:37:41 -04005567 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005568 }
5569
Erik Klinec75d4fa2017-02-15 19:59:17 +09005570 // Notify only this one new request of the current state. Transfer all the
5571 // current state by calling NetworkCapabilities and LinkProperties callbacks
5572 // so that callers can be guaranteed to have as close to atomicity in state
5573 // transfer as can be supported by this current API.
5574 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005575 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005576 if (nri.mPendingIntent != null) {
5577 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5578 // Attempt no subsequent state pushes where intents are involved.
5579 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005580 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005581
5582 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005583 }
5584
Robert Greenwalt8d482522015-06-24 13:23:42 -07005585 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005586 // The NetworkInfo we actually send out has no bearing on the real
5587 // state of affairs. For example, if the default connection is mobile,
5588 // and a request for HIPRI has just gone away, we need to pretend that
5589 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5590 // the state to DISCONNECTED, even though the network is of type MOBILE
5591 // and is still connected.
5592 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5593 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005594 if (state != DetailedState.DISCONNECTED) {
5595 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005596 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005597 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005598 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005599 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5600 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5601 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5602 if (info.isFailover()) {
5603 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5604 nai.networkInfo.setFailover(false);
5605 }
5606 if (info.getReason() != null) {
5607 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5608 }
5609 if (info.getExtraInfo() != null) {
5610 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5611 }
5612 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005613 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005614 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005615 if (newDefaultAgent != null) {
5616 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5617 newDefaultAgent.networkInfo);
5618 } else {
5619 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5620 }
5621 }
5622 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5623 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005624 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005625 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005626 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005627 }
5628 }
5629 }
5630
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005631 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005632 if (VDBG) {
5633 String notification = ConnectivityManager.getCallbackName(notifyType);
5634 log("notifyType " + notification + " for " + networkAgent.name());
5635 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005636 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5637 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005638 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5639 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005640 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5641 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005642 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005643 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005644 } else {
5645 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5646 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005648 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005649
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005650 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5651 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5652 }
5653
Jeff Sharkey69736342014-12-08 14:50:12 -08005654 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005655 * Returns the list of all interfaces that could be used by network traffic that does not
5656 * explicitly specify a network. This includes the default network, but also all VPNs that are
5657 * currently connected.
5658 *
5659 * Must be called on the handler thread.
5660 */
5661 private Network[] getDefaultNetworks() {
5662 ArrayList<Network> defaultNetworks = new ArrayList<>();
5663 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5664 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5665 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5666 defaultNetworks.add(nai.network);
5667 }
5668 }
5669 return defaultNetworks.toArray(new Network[0]);
5670 }
5671
5672 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005673 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5674 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005675 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005676 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005677 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005678 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005679 } catch (Exception ignored) {
5680 }
5681 }
5682
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005683 @Override
5684 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005685 int user = UserHandle.getUserId(Binder.getCallingUid());
5686 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005687 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005688 return mVpns.get(user).addAddress(address, prefixLength);
5689 }
5690 }
5691
5692 @Override
5693 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005694 int user = UserHandle.getUserId(Binder.getCallingUid());
5695 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005696 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005697 return mVpns.get(user).removeAddress(address, prefixLength);
5698 }
5699 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005700
5701 @Override
5702 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005703 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005704 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005705 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005706 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005707 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005708 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005709 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005710 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005711 }
5712 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005713 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005714
5715 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005716 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005717 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005718 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005719 }
5720
5721 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005722 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5723 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5724 enforceKeepalivePermission();
5725 mKeepaliveTracker.startNattKeepalive(
5726 getNetworkAgentInfoForNetwork(network),
5727 intervalSeconds, messenger, binder,
5728 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5729 }
5730
5731 @Override
5732 public void stopKeepalive(Network network, int slot) {
5733 mHandler.sendMessage(mHandler.obtainMessage(
5734 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5735 }
5736
5737 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005738 public void factoryReset() {
5739 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005740
5741 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5742 return;
5743 }
5744
Robin Lee3b3dd942015-05-12 18:14:58 +01005745 final int userId = UserHandle.getCallingUserId();
5746
Stuart Scottf1fb3972015-04-02 18:00:02 -07005747 // Turn airplane mode off
5748 setAirplaneMode(false);
5749
Stuart Scotte3e314d2015-04-20 14:07:45 -07005750 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5751 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005752 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005753 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005754 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005755 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005756 }
5757
Stuart Scotte3e314d2015-04-20 14:07:45 -07005758 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005759 // Remove always-on package
5760 synchronized (mVpns) {
5761 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5762 if (alwaysOnPackage != null) {
5763 setAlwaysOnVpnPackage(userId, null, false);
5764 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5765 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005766
Hugo Benichi69744342017-11-27 10:57:16 +09005767 // Turn Always-on VPN off
5768 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5769 final long ident = Binder.clearCallingIdentity();
5770 try {
5771 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5772 mLockdownEnabled = false;
5773 setLockdownTracker(null);
5774 } finally {
5775 Binder.restoreCallingIdentity(ident);
5776 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005777 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005778
Hugo Benichi69744342017-11-27 10:57:16 +09005779 // Turn VPN off
5780 VpnConfig vpnConfig = getVpnConfig(userId);
5781 if (vpnConfig != null) {
5782 if (vpnConfig.legacy) {
5783 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5784 } else {
5785 // Prevent this app (packagename = vpnConfig.user) from initiating
5786 // VPN connections in the future without user intervention.
5787 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005788
Hugo Benichi69744342017-11-27 10:57:16 +09005789 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5790 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005791 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005792 }
5793 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005794
5795 Settings.Global.putString(mContext.getContentResolver(),
5796 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005797 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005798
Ricky Wai44dcbde2018-01-23 04:09:45 +00005799 @Override
5800 public byte[] getNetworkWatchlistConfigHash() {
5801 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5802 if (nwm == null) {
5803 loge("Unable to get NetworkWatchlistManager");
5804 return null;
5805 }
5806 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5807 return nwm.getWatchlistConfigHash();
5808 }
5809
Paul Jensencf4c2c62015-07-01 14:16:32 -04005810 @VisibleForTesting
5811 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5812 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5813 return new NetworkMonitor(context, handler, nai, defaultRequest);
5814 }
Erik Kline48f12f22016-04-14 17:30:59 +09005815
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005816 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005817 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5818 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005819 }
5820
5821 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005822 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5823 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5824 }
5825
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005826 @VisibleForTesting
5827 public boolean hasService(String name) {
5828 return ServiceManager.checkService(name) != null;
5829 }
5830
Hugo Benichi64901e52017-10-19 14:42:40 +09005831 @VisibleForTesting
5832 protected IpConnectivityMetrics.Logger metricsLogger() {
5833 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5834 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005835 }
5836
5837 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005838 int[] transports = nai.networkCapabilities.getTransportTypes();
5839 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005840 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005841
5842 private static boolean toBool(int encodedBoolean) {
5843 return encodedBoolean != 0; // Only 0 means false.
5844 }
5845
5846 private static int encodeBool(boolean b) {
5847 return b ? 1 : 0;
5848 }
mswest46386886f2018-03-12 10:34:34 -07005849
5850 @Override
5851 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5852 FileDescriptor err, String[] args, ShellCallback callback,
5853 ResultReceiver resultReceiver) {
5854 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5855 }
5856
5857 private class ShellCmd extends ShellCommand {
5858
5859 @Override
5860 public int onCommand(String cmd) {
5861 if (cmd == null) {
5862 return handleDefaultCommands(cmd);
5863 }
5864 final PrintWriter pw = getOutPrintWriter();
5865 try {
5866 switch (cmd) {
5867 case "airplane-mode":
5868 final String action = getNextArg();
5869 if ("enable".equals(action)) {
5870 setAirplaneMode(true);
5871 return 0;
5872 } else if ("disable".equals(action)) {
5873 setAirplaneMode(false);
5874 return 0;
5875 } else if (action == null) {
5876 final ContentResolver cr = mContext.getContentResolver();
5877 final int enabled = Settings.Global.getInt(cr,
5878 Settings.Global.AIRPLANE_MODE_ON);
5879 pw.println(enabled == 0 ? "disabled" : "enabled");
5880 return 0;
5881 } else {
5882 onHelp();
5883 return -1;
5884 }
5885 default:
5886 return handleDefaultCommands(cmd);
5887 }
5888 } catch (Exception e) {
5889 pw.println(e);
5890 }
5891 return -1;
5892 }
5893
5894 @Override
5895 public void onHelp() {
5896 PrintWriter pw = getOutPrintWriter();
5897 pw.println("Connectivity service commands:");
5898 pw.println(" help");
5899 pw.println(" Print this help text.");
5900 pw.println(" airplane-mode [enable|disable]");
5901 pw.println(" Turn airplane mode on or off.");
5902 pw.println(" airplane-mode");
5903 pw.println(" Get airplane mode.");
5904 }
5905 }
5906}