blob: 4d39bdf0ffbbe5be048c8100a1b5b4fbe19939bb [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.
Erik Kline465ff3a2018-03-09 14:18:02 +0900913 final TetheringDependencies deps = new TetheringDependencies() {
914 @Override
915 public boolean isTetheringSupported() {
916 return ConnectivityService.this.isTetheringSupported();
917 }
918 };
Erik Kline47222fc2017-04-30 19:36:15 +0900919 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
920 IoThread.get().getLooper(), new MockableSystemProperties(),
921 deps);
922 }
923
Chalard Jeandda156a2018-01-10 21:19:32 +0900924 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900925 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900926 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900927 netCap.addCapability(NET_CAPABILITY_INTERNET);
928 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900929 if (transportType > -1) {
930 netCap.addTransportType(transportType);
931 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900932 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900933 }
934
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900935 // Used only for testing.
936 // TODO: Delete this and either:
937 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
938 // changing ContentResolver to make registerContentObserver non-final).
939 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
940 // by subclassing SettingsObserver.
941 @VisibleForTesting
942 void updateMobileDataAlwaysOn() {
943 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
944 }
945
Erik Klineda4bfa82015-04-30 12:58:40 +0900946 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900947 final boolean enable = toBool(Settings.Global.getInt(
948 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900949 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
950 if (enable == isEnabled) {
951 return; // Nothing to do.
952 }
953
954 if (enable) {
955 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900956 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900957 } else {
958 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
959 }
960 }
961
962 private void registerSettingsCallbacks() {
963 // Watch for global HTTP proxy changes.
964 mSettingsObserver.observe(
965 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
966 EVENT_APPLY_GLOBAL_HTTP_PROXY);
967
968 // Watch for whether or not to keep mobile data always on.
969 mSettingsObserver.observe(
970 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
971 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
972 }
973
Erik Klinea24d4592018-01-11 21:07:29 +0900974 private void registerPrivateDnsSettingsCallbacks() {
975 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
976 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
977 }
978 }
979
Robert Greenwalt34524f02014-05-18 16:22:10 -0700980 private synchronized int nextNetworkRequestId() {
981 return mNextNetworkRequestId++;
982 }
983
Paul Jensen67b0b072015-06-10 11:22:17 -0400984 @VisibleForTesting
985 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400986 synchronized (mNetworkForNetId) {
987 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
988 int netId = mNextNetId;
989 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
990 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500991 if (!mNetIdInUse.get(netId)) {
992 mNetIdInUse.put(netId, true);
993 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400994 }
995 }
996 }
997 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700998 }
999
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001002 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1003 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001005 state = nai.getNetworkState();
1006 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001008 final NetworkInfo info = new NetworkInfo(networkType, 0,
1009 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1011 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001012 final NetworkCapabilities capabilities = new NetworkCapabilities();
1013 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1014 !info.isRoaming());
1015 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001017 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 return state;
1020 } else {
1021 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001023 }
1024
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1026 if (network == null) {
1027 return null;
1028 }
1029 synchronized (mNetworkForNetId) {
1030 return mNetworkForNetId.get(network.netId);
1031 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001032 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001034 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001035 synchronized (mVpns) {
1036 if (!mLockdownEnabled) {
1037 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001038 Vpn vpn = mVpns.get(user);
1039 if (vpn != null && vpn.appliesToUid(uid)) {
1040 return vpn.getUnderlyingNetworks();
1041 }
1042 }
1043 }
1044 return null;
1045 }
1046
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001048 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001049
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001050 final Network[] networks = getVpnUnderlyingNetworks(uid);
1051 if (networks != null) {
1052 // getUnderlyingNetworks() returns:
1053 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1054 // empty array => the VPN explicitly said "no default network".
1055 // non-empty array => the VPN specified one or more default networks; we use the
1056 // first one.
1057 if (networks.length > 0) {
1058 nai = getNetworkAgentInfoForNetwork(networks[0]);
1059 } else {
1060 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001061 }
1062 }
1063
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001064 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 return nai.getNetworkState();
1066 } else {
1067 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001069 }
1070
1071 /**
1072 * Check if UID should be blocked from using the network with the given LinkProperties.
1073 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001074 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1075 boolean ignoreBlocked) {
1076 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001077 if (ignoreBlocked) {
1078 return false;
1079 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001080 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001081 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1082 if (isSystem(uid)) {
1083 return false;
1084 }
Robin Lee17e61832016-05-09 13:46:28 +01001085 synchronized (mVpns) {
1086 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1087 if (vpn != null && vpn.isBlockingUid(uid)) {
1088 return true;
1089 }
1090 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001091 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001092 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 }
1094
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001095 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001096 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1097 return;
1098 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001099 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001100 synchronized (mBlockedAppUids) {
1101 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001102 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001103 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001104 blocked = false;
1105 } else {
1106 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001107 }
1108 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001109 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1110 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1111 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001112 }
1113
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001114 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001115 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1116 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001117 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001118 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001120 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1121
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001123 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001124 }
Hugo Benichi69744342017-11-27 10:57:16 +09001125 synchronized (mVpns) {
1126 if (mLockdownTracker != null) {
1127 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1128 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001129 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 }
1131
1132 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 * Return NetworkInfo for the active (i.e., connected) network interface.
1134 * It is assumed that at most one network is active at a time. If more
1135 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001136 * @return the info for the active network, or {@code null} if none is
1137 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001139 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 enforceAccessPermission();
1142 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1146 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148
Paul Jensen31a94f42015-02-13 14:18:39 -05001149 @Override
1150 public Network getActiveNetwork() {
1151 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001153 }
1154
1155 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001157 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001159 }
1160
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001162 final int user = UserHandle.getUserId(uid);
1163 int vpnNetId = NETID_UNSET;
1164 synchronized (mVpns) {
1165 final Vpn vpn = mVpns.get(user);
1166 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1167 }
1168 NetworkAgentInfo nai;
1169 if (vpnNetId != NETID_UNSET) {
1170 synchronized (mNetworkForNetId) {
1171 nai = mNetworkForNetId.get(vpnNetId);
1172 }
1173 if (nai != null) return nai.network;
1174 }
1175 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 if (nai != null
1177 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1178 nai = null;
1179 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001180 return nai != null ? nai.network : null;
1181 }
1182
Lorenzo Colitti18660282016-07-04 12:55:44 +09001183 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001184 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1185 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 final int uid = Binder.getCallingUid();
1187 NetworkState state = getUnfilteredActiveNetworkState(uid);
1188 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001189 }
1190
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001191 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001193 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001194 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001195 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001196 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
1198
1199 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 public NetworkInfo getNetworkInfo(int networkType) {
1201 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001202 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001203 if (getVpnUnderlyingNetworks(uid) != null) {
1204 // A VPN is active, so we may need to return one of its underlying networks. This
1205 // information is not available in LegacyTypeTracker, so we have to get it from
1206 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001207 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001208 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001209 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001210 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001211 }
1212 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001213 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 }
1216
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001218 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001222 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001223 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001224 return state.networkInfo;
1225 } else {
1226 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001227 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 }
1229
1230 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 public NetworkInfo[] getAllNetworkInfo() {
1232 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001233 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001234 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1235 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 NetworkInfo info = getNetworkInfo(networkType);
1237 if (info != null) {
1238 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001241 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
1243
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001244 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001245 public Network getNetworkForType(int networkType) {
1246 enforceAccessPermission();
1247 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001248 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1249 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001250 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001251 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001253 }
1254
1255 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001256 public Network[] getAllNetworks() {
1257 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001258 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001259 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001260 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001261 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001262 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001263 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001264 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001265 }
1266
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001267 @Override
1268 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1269 // The basic principle is: if an app's traffic could possibly go over a
1270 // network, without the app doing anything multinetwork-specific,
1271 // (hence, by "default"), then include that network's capabilities in
1272 // the array.
1273 //
1274 // In the normal case, app traffic only goes over the system's default
1275 // network connection, so that's the only network returned.
1276 //
1277 // With a VPN in force, some app traffic may go into the VPN, and thus
1278 // over whatever underlying networks the VPN specifies, while other app
1279 // traffic may go over the system default network (e.g.: a split-tunnel
1280 // VPN, or an app disallowed by the VPN), so the set of networks
1281 // returned includes the VPN's underlying networks and the system
1282 // default.
1283 enforceAccessPermission();
1284
1285 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1286
1287 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001288 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001289 if (nc != null) {
1290 result.put(nai.network, nc);
1291 }
1292
Hugo Benichi69744342017-11-27 10:57:16 +09001293 synchronized (mVpns) {
1294 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001295 Vpn vpn = mVpns.get(userId);
1296 if (vpn != null) {
1297 Network[] networks = vpn.getUnderlyingNetworks();
1298 if (networks != null) {
1299 for (Network network : networks) {
1300 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001301 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001302 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001303 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001304 }
1305 }
1306 }
1307 }
1308 }
1309 }
1310
1311 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1312 out = result.values().toArray(out);
1313 return out;
1314 }
1315
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001316 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001317 public boolean isNetworkSupported(int networkType) {
1318 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001319 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001320 }
1321
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001322 /**
1323 * Return LinkProperties for the active (i.e., connected) default
1324 * network interface. It is assumed that at most one default network
1325 * is active at a time. If more than one is active, it is indeterminate
1326 * which will be returned.
1327 * @return the ip properties for the active network, or {@code null} if
1328 * none is active
1329 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001330 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001331 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001332 enforceAccessPermission();
1333 final int uid = Binder.getCallingUid();
1334 NetworkState state = getUnfilteredActiveNetworkState(uid);
1335 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001336 }
1337
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001338 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001339 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001340 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1342 if (nai != null) {
1343 synchronized (nai) {
1344 return new LinkProperties(nai.linkProperties);
1345 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001346 }
1347 return null;
1348 }
1349
Robert Greenwalt12e67352014-05-13 21:41:06 -07001350 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001351 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001352 public LinkProperties getLinkProperties(Network network) {
1353 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001354 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1355 }
1356
1357 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1358 if (nai == null) {
1359 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001360 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001361 synchronized (nai) {
1362 return new LinkProperties(nai.linkProperties);
1363 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001364 }
1365
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001366 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001367 if (nai != null) {
1368 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001369 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001370 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1371 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001372 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001373 }
1374 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001375 return null;
1376 }
1377
1378 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001379 public NetworkCapabilities getNetworkCapabilities(Network network) {
1380 enforceAccessPermission();
1381 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1382 }
1383
Chalard Jeanb552c462018-02-21 18:43:54 +09001384 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1385 NetworkCapabilities nc, int callerPid, int callerUid) {
1386 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001387 return new NetworkCapabilities(nc).setUids(null);
1388 }
1389
Chalard Jeanb552c462018-02-21 18:43:54 +09001390 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1391 if (!checkSettingsPermission()) {
1392 nc.setSingleUid(Binder.getCallingUid());
1393 }
1394 }
1395
Chalard Jean26aa91a2018-03-20 19:13:57 +09001396 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1397 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1398 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1399 }
1400 }
1401
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001402 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001403 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001404 // Require internal since we're handing out IMSI details
1405 enforceConnectivityInternalPermission();
1406
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001407 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001408 for (Network network : getAllNetworks()) {
1409 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1410 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001411 // TODO (b/73321673) : NetworkState contains a copy of the
1412 // NetworkCapabilities, which may contain UIDs of apps to which the
1413 // network applies. Should the UIDs be cleared so as not to leak or
1414 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001415 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001416 }
1417 }
1418 return result.toArray(new NetworkState[result.size()]);
1419 }
1420
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001421 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001422 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001423 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001424 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1425 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1426 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001427 }
1428
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001429 @Override
1430 public boolean isActiveNetworkMetered() {
1431 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001432
Eric Enslenc81ef192018-02-07 18:03:53 -08001433 final int uid = Binder.getCallingUid();
1434 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001435 if (caps != null) {
1436 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1437 } else {
1438 // Always return the most conservative value
1439 return true;
1440 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001441 }
1442
Jeff Sharkey216c1812012-08-05 14:29:23 -07001443 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1444 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001445 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001446 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001447 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001448 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001449 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001450
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001451 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 * Ensure that a network route exists to deliver traffic to the specified
1453 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001454 * @param networkType the type of the network over which traffic to the
1455 * specified host is to be routed
1456 * @param hostAddress the IP address of the host to which the route is
1457 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * @return {@code true} on success, {@code false} on failure
1459 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001460 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001461 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001463 if (mProtectedNetworks.contains(networkType)) {
1464 enforceConnectivityInternalPermission();
1465 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001466
Chad Brubakerc0234532014-02-14 13:24:29 -08001467 InetAddress addr;
1468 try {
1469 addr = InetAddress.getByAddress(hostAddress);
1470 } catch (UnknownHostException e) {
1471 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1472 return false;
1473 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001476 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 return false;
1478 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001479
1480 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1481 if (nai == null) {
1482 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1483 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1484 } else {
1485 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1486 }
1487 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001488 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001489
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001490 DetailedState netState;
1491 synchronized (nai) {
1492 netState = nai.networkInfo.getDetailedState();
1493 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001494
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001495 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001496 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001497 log("requestRouteToHostAddress on down network "
1498 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001499 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001500 }
1501 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001503
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001504 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001505 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001506 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001507 LinkProperties lp;
1508 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001509 synchronized (nai) {
1510 lp = nai.linkProperties;
1511 netId = nai.network.netId;
1512 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001513 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001514 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1515 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001516 } finally {
1517 Binder.restoreCallingIdentity(token);
1518 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001519 }
1520
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001521 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001522 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001523 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001524 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001525 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001526 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001527 if (bestRoute.getGateway().equals(addr)) {
1528 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001529 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001530 } else {
1531 // if we will connect to this through another route, add a direct route
1532 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001533 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001534 }
1535 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001536 if (DBG) log("Adding legacy route " + bestRoute +
1537 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001538 try {
1539 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1540 } catch (Exception e) {
1541 // never crash - catch them all
1542 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001543 return false;
1544 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001545 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547
Jeff Sharkey75d31892018-01-18 22:01:59 +09001548 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001549 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001550 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001551 // TODO: notify UID when it has requested targeted updates
1552 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001553 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001554 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001555 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001556 if (restrictBackground) {
1557 log("onRestrictBackgroundChanged(true): disabling tethering");
1558 mTethering.untetherAll();
1559 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001560 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001561 };
1562
Robin Lee3b3dd942015-05-12 18:14:58 +01001563 /**
1564 * Require that the caller is either in the same user or has appropriate permission to interact
1565 * across users.
1566 *
1567 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1568 */
1569 private void enforceCrossUserPermission(int userId) {
1570 if (userId == UserHandle.getCallingUserId()) {
1571 // Not a cross-user call.
1572 return;
1573 }
1574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1576 "ConnectivityService");
1577 }
1578
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001579 private void enforceInternetPermission() {
1580 mContext.enforceCallingOrSelfPermission(
1581 android.Manifest.permission.INTERNET,
1582 "ConnectivityService");
1583 }
1584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.ACCESS_NETWORK_STATE,
1588 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001592 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594
Charles He36738632017-05-15 17:07:18 +01001595 private void enforceSettingsPermission() {
1596 mContext.enforceCallingOrSelfPermission(
1597 android.Manifest.permission.NETWORK_SETTINGS,
1598 "ConnectivityService");
1599 }
1600
Chalard Jeanb552c462018-02-21 18:43:54 +09001601 private boolean checkSettingsPermission() {
1602 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1603 android.Manifest.permission.NETWORK_SETTINGS);
1604 }
1605
1606 private boolean checkSettingsPermission(int pid, int uid) {
1607 return PERMISSION_GRANTED == mContext.checkPermission(
1608 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1609 }
1610
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001611 private void enforceTetherAccessPermission() {
1612 mContext.enforceCallingOrSelfPermission(
1613 android.Manifest.permission.ACCESS_NETWORK_STATE,
1614 "ConnectivityService");
1615 }
1616
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001617 private void enforceConnectivityInternalPermission() {
1618 mContext.enforceCallingOrSelfPermission(
1619 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1620 "ConnectivityService");
1621 }
1622
Hugo Benichi514da602016-07-19 15:59:27 +09001623 private void enforceConnectivityRestrictedNetworksPermission() {
1624 try {
1625 mContext.enforceCallingOrSelfPermission(
1626 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1627 "ConnectivityService");
1628 return;
1629 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1630 enforceConnectivityInternalPermission();
1631 }
1632
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001633 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001634 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001635 }
1636
Lorenzo Colitti18660282016-07-04 12:55:44 +09001637 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001638 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001639 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001640 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001641 }
1642
1643 private void sendInetConditionBroadcast(NetworkInfo info) {
1644 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1645 }
1646
Wink Saville628b0852011-08-04 15:01:58 -07001647 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001648 synchronized (mVpns) {
1649 if (mLockdownTracker != null) {
1650 info = new NetworkInfo(info);
1651 mLockdownTracker.augmentNetworkInfo(info);
1652 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001653 }
1654
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001655 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001656 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001657 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (info.isFailover()) {
1659 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1660 info.setFailover(false);
1661 }
1662 if (info.getReason() != null) {
1663 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1664 }
1665 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001666 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1667 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001669 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001670 return intent;
1671 }
1672
1673 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1674 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1675 }
1676
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001677 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001678 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1679 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1680 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001681 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001682 final long ident = Binder.clearCallingIdentity();
1683 try {
1684 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1685 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1686 } finally {
1687 Binder.restoreCallingIdentity(ident);
1688 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001689 }
1690
Mike Lockwood0f79b542009-08-14 14:18:49 -04001691 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001692 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001693 if (!mSystemReady) {
1694 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001695 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001696 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001697 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001698 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001699 }
1700
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001701 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001702 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001703 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001704 final NetworkInfo ni = intent.getParcelableExtra(
1705 ConnectivityManager.EXTRA_NETWORK_INFO);
1706 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1707 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1708 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001709 } else {
1710 BroadcastOptions opts = BroadcastOptions.makeBasic();
1711 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1712 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001713 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001714 final IBatteryStats bs = BatteryStatsService.getService();
1715 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001716 bs.noteConnectivityChanged(intent.getIntExtra(
1717 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1718 ni != null ? ni.getState().toString() : "?");
1719 } catch (RemoteException e) {
1720 }
Chad Brubakerac925012018-03-08 10:37:09 -08001721 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001722 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001723 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001724 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001725 } finally {
1726 Binder.restoreCallingIdentity(ident);
1727 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001728 }
1729 }
1730
1731 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001732 loadGlobalProxy();
1733
Hugo Benichi20035e02017-04-26 14:53:28 +09001734 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001735 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001736 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001737 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001738 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001739 }
1740 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001741 // load the global proxy at startup
1742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001743
Robin Lee244ce8e2016-01-05 18:03:46 +00001744 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1745 // for user to unlock device too.
1746 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001747
Erik Klineda4bfa82015-04-30 12:58:40 +09001748 // Configure whether mobile data is always on.
1749 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1750
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001751 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001752
1753 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001758 *
1759 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001760 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001761 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1763 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001764
1765 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001767
Robert Greenwalt7b816022014-04-18 15:25:25 -07001768 if (networkAgent.networkCapabilities.hasTransport(
1769 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001770 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1771 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001772 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001773 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001774 } else if (networkAgent.networkCapabilities.hasTransport(
1775 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001776 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1777 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001778 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001779 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001780 } else {
1781 // do not track any other networks
1782 timeout = 0;
1783 }
1784
Robert Greenwalt7b816022014-04-18 15:25:25 -07001785 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001786 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001787 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001788 } catch (Exception e) {
1789 // You shall not crash!
1790 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001791 }
1792 }
1793 }
1794
1795 /**
1796 * Remove data activity tracking when network disconnects.
1797 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1799 final String iface = networkAgent.linkProperties.getInterfaceName();
1800 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001801
Robert Greenwalt7b816022014-04-18 15:25:25 -07001802 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1803 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001804 try {
1805 // the call fails silently if no idletimer setup for this interface
1806 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001807 } catch (Exception e) {
1808 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001809 }
1810 }
1811 }
1812
1813 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001814 * Reads the network specific MTU size from reources.
1815 * and set it on it's iface.
1816 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1818 final String iface = newLp.getInterfaceName();
1819 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001820 if (oldLp == null && mtu == 0) {
1821 // Silently ignore unset MTU value.
1822 return;
1823 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1825 if (VDBG) log("identical MTU - not setting");
1826 return;
1827 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001828 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001829 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001830 return;
1831 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001832
w1997615afd812014-08-05 15:18:11 -07001833 // Cannot set MTU without interface name
1834 if (TextUtils.isEmpty(iface)) {
1835 loge("Setting MTU size with null iface.");
1836 return;
1837 }
1838
Robert Greenwalt7b816022014-04-18 15:25:25 -07001839 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001840 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001841 mNetd.setMtu(iface, mtu);
1842 } catch (Exception e) {
1843 Slog.e(TAG, "exception in setMtu()" + e);
1844 }
1845 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001846
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001847 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001848 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1849
1850 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001851 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001852 protected MockableSystemProperties getSystemProperties() {
1853 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001854 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001855
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001856 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1857 if (isDefaultNetwork(nai) == false) {
1858 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001859 }
1860
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001861 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1862 String[] values = null;
1863 if (tcpBufferSizes != null) {
1864 values = tcpBufferSizes.split(",");
1865 }
1866
1867 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001868 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001869 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1870 values = tcpBufferSizes.split(",");
1871 }
1872
1873 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1874
1875 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001876 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001877
1878 final String prefix = "/sys/kernel/ipv4/tcp_";
1879 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1880 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1881 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1882 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1883 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1884 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1885 mCurrentTcpBufferSizes = tcpBufferSizes;
1886 } catch (IOException e) {
1887 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001888 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001889
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001890 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001891 Settings.Global.TCP_DEFAULT_INIT_RWND,
1892 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001893 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1894 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001895 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001896 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001897 }
1898
Robert Greenwalt562cc542014-05-15 18:07:26 -07001899 @Override
1900 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001901 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 NETWORK_RESTORE_DELAY_PROP_NAME);
1903 if(restoreDefaultNetworkDelayStr != null &&
1904 restoreDefaultNetworkDelayStr.length() != 0) {
1905 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001906 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 } catch (NumberFormatException e) {
1908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001910 // if the system property isn't set, use the value for the apn type
1911 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1912
1913 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1914 (mNetConfigs[networkType] != null)) {
1915 ret = mNetConfigs[networkType].restoreTime;
1916 }
1917 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
1919
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001920 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001921 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001922 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001923 }
1924 return false;
1925 }
1926
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001927 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1928 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1929 final long DIAG_TIME_MS = 5000;
1930 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1931 // Start gathering diagnostic information.
1932 netDiags.add(new NetworkDiagnostics(
1933 nai.network,
1934 new LinkProperties(nai.linkProperties), // Must be a copy.
1935 DIAG_TIME_MS));
1936 }
1937
1938 for (NetworkDiagnostics netDiag : netDiags) {
1939 pw.println();
1940 netDiag.waitForMeasurements();
1941 netDiag.dump(pw);
1942 }
1943 }
1944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001946 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001947 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1948 }
1949
1950 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001951 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001952 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001953 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001954
Erik Kline7747fd42017-05-12 16:52:48 +09001955 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001956 dumpNetworkDiagnostics(pw);
1957 return;
Erik Klineee363c42017-05-29 09:11:03 +09001958 } else if (argsContain(args, TETHERING_ARG)) {
1959 mTethering.dump(fd, pw, args);
1960 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001961 }
Erik Kline379747a2015-06-05 17:47:34 +09001962
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001965 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001966 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001967 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001968 pw.println();
1969
Paul Jensen85cf78e2015-06-25 13:25:07 -04001970 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.print("Active default network: ");
1972 if (defaultNai == null) {
1973 pw.println("none");
1974 } else {
1975 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001977 pw.println();
1978
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001980 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1982 pw.println(nai.toString());
1983 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001984 pw.println(String.format(
1985 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1986 nai.numForegroundNetworkRequests(),
1987 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1988 nai.numBackgroundNetworkRequests(),
1989 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001991 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1992 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001993 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 pw.decreaseIndent();
1995 pw.println("Lingered:");
1996 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001997 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001998 pw.decreaseIndent();
1999 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002000 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002001 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002002 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002003
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002004 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002005 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002006 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2007 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002008 }
2009 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002010 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002011
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002012 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002013
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002014 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002015 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002016
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002017 pw.println();
2018 mKeepaliveTracker.dump(pw);
2019
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002020 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002021 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002022
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002023 pw.println();
2024 mMultipathPolicyTracker.dump(pw);
2025
Erik Kline7747fd42017-05-12 16:52:48 +09002026 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002027 pw.println();
2028 synchronized (mValidationLogs) {
2029 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002030 for (ValidationLog p : mValidationLogs) {
2031 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002032 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002033 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002034 pw.decreaseIndent();
2035 }
2036 }
Erik Kline7523eb32015-07-09 18:24:03 +09002037
2038 pw.println();
2039 pw.println("mNetworkRequestInfoLogs (most recent first):");
2040 pw.increaseIndent();
2041 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2042 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002043
2044 pw.println();
2045 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2046 pw.increaseIndent();
2047 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2048 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002049
2050 pw.println();
2051 pw.println("NetTransition WakeLock activity (most recent first):");
2052 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002053 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2054 pw.println("total releases: " + mTotalWakelockReleases);
2055 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2056 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2057 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2058 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2059 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2060 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002061 mWakelockLogs.reverseDump(fd, pw, args);
2062 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002066 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002067 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002068 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002069 if (officialNai != null && officialNai.equals(nai)) return true;
2070 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002071 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002072 " - " + nai);
2073 }
2074 return false;
2075 }
2076
Robert Greenwalt42acef32009-08-12 16:08:25 -07002077 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002078 private class NetworkStateTrackerHandler extends Handler {
2079 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002080 super(looper);
2081 }
2082
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002083 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002085 default:
2086 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002087 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002088 handleAsyncChannelHalfConnect(msg);
2089 break;
2090 }
2091 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2092 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2093 if (nai != null) nai.asyncChannel.disconnect();
2094 break;
2095 }
2096 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2097 handleAsyncChannelDisconnected(msg);
2098 break;
2099 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 }
2101 return true;
2102 }
2103
2104 private void maybeHandleNetworkAgentMessage(Message msg) {
2105 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2106 if (nai == null) {
2107 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002108 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 }
2110 return;
2111 }
2112
2113 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2116 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002117 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2118 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002119 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002120 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002121 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002122 break;
2123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002125 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 break;
2127 }
2128 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 updateNetworkInfo(nai, info);
2131 break;
2132 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002133 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002134 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002135 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002136 break;
2137 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002138 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002139 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2140 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002141 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002142 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002143 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002144 break;
2145 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002146 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002147 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2148 break;
2149 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002150 }
2151 }
2152
2153 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2154 switch (msg.what) {
2155 default:
2156 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002157 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002158 final NetworkAgentInfo nai;
2159 synchronized (mNetworkForNetId) {
2160 nai = mNetworkForNetId.get(msg.arg2);
2161 }
Erik Klinea24d4592018-01-11 21:07:29 +09002162 if (nai == null) break;
2163
2164 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2165 final boolean wasValidated = nai.lastValidated;
2166 final boolean wasDefault = isDefaultNetwork(nai);
2167
2168 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2169 ? (PrivateDnsConfig) msg.obj : null;
2170 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2171
2172 final boolean reevaluationRequired;
2173 final String logMsg;
2174 if (valid) {
2175 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2176 logMsg = (DBG && (privateDnsCfg != null))
2177 ? " with " + privateDnsCfg.toString() : "";
2178 } else {
2179 reevaluationRequired = false;
2180 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2181 ? " with redirect to " + redirectUrl : "";
2182 }
2183 if (DBG) {
2184 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2185 }
2186 // If there is a change in Private DNS configuration,
2187 // trigger reevaluation of the network to test it.
2188 if (reevaluationRequired) {
2189 nai.networkMonitor.sendMessage(
2190 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2191 break;
2192 }
2193 if (valid != nai.lastValidated) {
2194 if (wasDefault) {
2195 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2196 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002197 }
Erik Klinea24d4592018-01-11 21:07:29 +09002198 final int oldScore = nai.getCurrentScore();
2199 nai.lastValidated = valid;
2200 nai.everValidated |= valid;
2201 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2202 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2203 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2204 }
2205 updateInetCondition(nai);
2206 // Let the NetworkAgent know the state of its network
2207 Bundle redirectUrlBundle = new Bundle();
2208 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2209 nai.asyncChannel.sendMessage(
2210 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2211 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2212 0, redirectUrlBundle);
2213 if (wasValidated && !nai.lastValidated) {
2214 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002216 break;
2217 }
Paul Jensen869868be2014-05-15 10:33:05 -04002218 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002219 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002220 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002221 final NetworkAgentInfo nai;
2222 synchronized (mNetworkForNetId) {
2223 nai = mNetworkForNetId.get(netId);
2224 }
Calvin Onbe96da12016-10-11 15:10:46 -07002225 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002226 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002227 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002228 nai.lastCaptivePortalDetected = visible;
2229 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002230 if (nai.lastCaptivePortalDetected &&
2231 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2232 if (DBG) log("Avoiding captive portal network: " + nai.name());
2233 nai.asyncChannel.sendMessage(
2234 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2235 teardownUnneededNetwork(nai);
2236 break;
2237 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002238 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002239 }
2240 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002241 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002242 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002243 if (nai == null) {
2244 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2245 break;
2246 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002247 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002248 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002249 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 }
Paul Jensen869868be2014-05-15 10:33:05 -04002252 break;
2253 }
Erik Klinea24d4592018-01-11 21:07:29 +09002254 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2255 final NetworkAgentInfo nai;
2256 synchronized (mNetworkForNetId) {
2257 nai = mNetworkForNetId.get(msg.arg2);
2258 }
2259 if (nai == null) break;
2260
2261 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2262 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2263 if (nai.lastValidated && reevaluationRequired) {
2264 nai.networkMonitor.sendMessage(
2265 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2266 }
2267 break;
2268 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002269 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002270 return true;
2271 }
2272
Calvin Onbe96da12016-10-11 15:10:46 -07002273 private int getCaptivePortalMode() {
2274 return Settings.Global.getInt(mContext.getContentResolver(),
2275 Settings.Global.CAPTIVE_PORTAL_MODE,
2276 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2277 }
2278
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002279 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2280 switch (msg.what) {
2281 default:
2282 return false;
2283 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2284 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2285 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2286 handleLingerComplete(nai);
2287 }
2288 break;
2289 }
2290 }
2291 return true;
2292 }
2293
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002294 @Override
2295 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 if (!maybeHandleAsyncChannelMessage(msg) &&
2297 !maybeHandleNetworkMonitorMessage(msg) &&
2298 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002299 maybeHandleNetworkAgentMessage(msg);
2300 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002301 }
2302 }
2303
Erik Klinea24d4592018-01-11 21:07:29 +09002304 private void handlePrivateDnsSettingsChanged() {
2305 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2306
2307 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2308 // Private DNS only ever applies to networks that might provide
2309 // Internet access and therefore also require validation.
2310 if (!NetworkMonitor.isValidationRequired(
2311 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2312 continue;
2313 }
2314
2315 // Notify the NetworkMonitor thread in case it needs to cancel or
2316 // schedule DNS resolutions. If a DNS resolution is required the
2317 // result will be sent back to us.
2318 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2319
2320 if (!cfg.inStrictMode()) {
2321 // No strict mode hostname DNS resolution needed, so just update
2322 // DNS settings directly. In opportunistic and "off" modes this
2323 // just reprograms netd with the network-supplied DNS servers
2324 // (and of course the boolean of whether or not to attempt TLS).
2325 //
2326 // TODO: Consider code flow parity with strict mode, i.e. having
2327 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2328 // performing this call at that time.
2329 updatePrivateDns(nai, cfg);
2330 }
2331 }
2332 }
2333
2334 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2335 final boolean reevaluationRequired = true;
2336 final boolean dontReevaluate = false;
2337
2338 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2339 updateDnses(nai.linkProperties, null, nai.network.netId);
2340
2341 if (newCfg == null) {
2342 if (oldCfg == null) return dontReevaluate;
2343 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2344 }
2345
2346 if (oldCfg == null) {
2347 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2348 }
2349
2350 if (oldCfg.useTls != newCfg.useTls) {
2351 return reevaluationRequired;
2352 }
2353
2354 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2355 return reevaluationRequired;
2356 }
2357
2358 return dontReevaluate;
2359 }
2360
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002361 private void updateLingerState(NetworkAgentInfo nai, long now) {
2362 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2363 // 2. If the network was lingering and there are now requests, unlinger it.
2364 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2365 // one lingered request, start lingering.
2366 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002367 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002368 if (DBG) log("Unlingering " + nai.name());
2369 nai.unlinger();
2370 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002371 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002372 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002373 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002374 nai.linger();
2375 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2376 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2377 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002378 }
2379
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 private void handleAsyncChannelHalfConnect(Message msg) {
2381 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002382 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002383 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2384 if (VDBG) log("NetworkFactory connected");
2385 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002386 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002387 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002388 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002389 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002390 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002391 }
2392 } else {
2393 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002394 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 }
2396 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2397 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2398 if (VDBG) log("NetworkAgent connected");
2399 // A network agent has requested a connection. Establish the connection.
2400 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2401 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2402 } else {
2403 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002404 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002405 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002406 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002407 synchronized (mNetworkForNetId) {
2408 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002409 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002410 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002411 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002412 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002413 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002414 }
2415 }
2416 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002417
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 private void handleAsyncChannelDisconnected(Message msg) {
2419 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2420 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002421 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002422 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002423 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002425 // TODO - if we move the logic to the network agent (have them disconnect
2426 // because they lost all their requests or because their score isn't good)
2427 // then they would disconnect organically, report their new state and then
2428 // disconnect the channel.
2429 if (nai.networkInfo.isConnected()) {
2430 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2431 null, null);
2432 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002433 final boolean wasDefault = isDefaultNetwork(nai);
2434 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002435 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002436 // Log default network disconnection before required book-keeping.
2437 // Let rematchAllNetworksAndRequests() below record a new default network event
2438 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2439 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002440 long now = SystemClock.elapsedRealtime();
2441 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002442 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002443 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002444 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2445 // by other networks that are already connected. Perhaps that can be done by
2446 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2447 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002448 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002449 mKeepaliveTracker.handleStopAllKeepalives(nai,
2450 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002451 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2452 // Disable wakeup packet monitoring for each interface.
2453 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2454 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002455 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002456 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002457 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002458 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002459 // Remove the NetworkAgent, but don't mark the netId as
2460 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002461 mNetworkForNetId.remove(nai.network.netId);
2462 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002463 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002464 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2465 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002466 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002467 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002468 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002469 sendUpdatedScoreToFactories(request, 0);
2470 }
2471 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002472 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002473 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002474 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002475 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002476 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002477 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002478 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002479 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002480 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002481 if (nai.created) {
2482 // Tell netd to clean up the configuration for this network
2483 // (routing rules, DNS, etc).
2484 // This may be slow as it requires a lot of netd shelling out to ip and
2485 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2486 // after we've rematched networks with requests which should make a potential
2487 // fallback network the default or requested a new network from the
2488 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2489 // long time.
2490 try {
2491 mNetd.removeNetwork(nai.network.netId);
2492 } catch (Exception e) {
2493 loge("Exception removing network: " + e);
2494 }
Erik Klinea24d4592018-01-11 21:07:29 +09002495 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002496 }
2497 synchronized (mNetworkForNetId) {
2498 mNetIdInUse.delete(nai.network.netId);
2499 }
2500 } else {
2501 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2502 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002503 }
2504 }
2505
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002506 // If this method proves to be too slow then we can maintain a separate
2507 // pendingIntent => NetworkRequestInfo map.
2508 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2509 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2510 Intent intent = pendingIntent.getIntent();
2511 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2512 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2513 if (existingPendingIntent != null &&
2514 existingPendingIntent.getIntent().filterEquals(intent)) {
2515 return entry.getValue();
2516 }
2517 }
2518 return null;
2519 }
2520
2521 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2522 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2523
2524 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2525 if (existingRequest != null) { // remove the existing request.
2526 if (DBG) log("Replacing " + existingRequest.request + " with "
2527 + nri.request + " because their intents matched.");
2528 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2529 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002530 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002531 }
2532
Erik Klineda4bfa82015-04-30 12:58:40 +09002533 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002534 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002535 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002536 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002537 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002538 if (nri.request.networkCapabilities.hasSignalStrength() &&
2539 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2540 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002541 }
2542 }
2543 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002544 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002545 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002546 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002547 }
2548 }
2549
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002550 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2551 int callingUid) {
2552 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2553 if (nri != null) {
2554 handleReleaseNetworkRequest(nri.request, callingUid);
2555 }
2556 }
2557
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002558 // Determines whether the network is the best (or could become the best, if it validated), for
2559 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2560 // on the value of reason:
2561 //
2562 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2563 // then it should be torn down.
2564 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2565 // then it should be lingered.
2566 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2567 final int numRequests;
2568 switch (reason) {
2569 case TEARDOWN:
2570 numRequests = nai.numRequestNetworkRequests();
2571 break;
2572 case LINGER:
2573 numRequests = nai.numForegroundNetworkRequests();
2574 break;
2575 default:
2576 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2577 return true;
2578 }
2579
2580 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002581 return false;
2582 }
Paul Jensene0988542015-06-25 15:30:08 -04002583 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002584 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2585 // Background requests don't affect lingering.
2586 continue;
2587 }
2588
Paul Jensene0988542015-06-25 15:30:08 -04002589 // If this Network is already the highest scoring Network for a request, or if
2590 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002591 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002592 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002593 // Note that this catches two important cases:
2594 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2595 // is currently satisfying the request. This is desirable when
2596 // cellular ends up validating but WiFi does not.
2597 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002598 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002599 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002600 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002601 nai.getCurrentScoreAsValidated())) {
2602 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002603 }
2604 }
Paul Jensene0988542015-06-25 15:30:08 -04002605 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002606 }
2607
Erik Klineacdd6392016-07-07 16:50:58 +09002608 private NetworkRequestInfo getNriForAppRequest(
2609 NetworkRequest request, int callingUid, String requestedOperation) {
2610 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2611
Robert Greenwalt9258c642014-03-26 16:47:06 -07002612 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002613 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002614 log(String.format("UID %d attempted to %s for unowned request %s",
2615 callingUid, requestedOperation, nri));
2616 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002617 }
Erik Klineacdd6392016-07-07 16:50:58 +09002618 }
2619
2620 return nri;
2621 }
2622
Erik Kline57faba92015-11-25 12:49:38 +09002623 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002624 if (mNetworkRequests.get(nri.request) == null) {
2625 return;
Erik Kline57faba92015-11-25 12:49:38 +09002626 }
Hugo Benichicd952782017-09-20 11:20:14 +09002627 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002628 return;
2629 }
2630 if (VDBG || (DBG && nri.request.isRequest())) {
2631 log("releasing " + nri.request + " (timeout)");
2632 }
2633 handleRemoveNetworkRequest(nri);
2634 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002635 }
2636
Erik Klineacdd6392016-07-07 16:50:58 +09002637 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002638 final NetworkRequestInfo nri =
2639 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2640 if (nri == null) {
2641 return;
Erik Kline57faba92015-11-25 12:49:38 +09002642 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002643 if (VDBG || (DBG && nri.request.isRequest())) {
2644 log("releasing " + nri.request + " (release request)");
2645 }
2646 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002647 }
Erik Klineacdd6392016-07-07 16:50:58 +09002648
Hugo Benichidba33db2017-03-23 22:40:44 +09002649 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002650 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002651 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002652
Erik Klineacdd6392016-07-07 16:50:58 +09002653 synchronized (mUidToNetworkRequestCount) {
2654 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2655 if (requests < 1) {
2656 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2657 nri.mUid);
2658 } else if (requests == 1) {
2659 mUidToNetworkRequestCount.removeAt(
2660 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2661 } else {
2662 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2663 }
2664 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002665
Erik Klineacdd6392016-07-07 16:50:58 +09002666 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2667 if (nri.request.isRequest()) {
2668 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002669 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002670 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002671 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002672 nai.removeRequest(nri.request.requestId);
2673 if (VDBG) {
2674 log(" Removing from current network " + nai.name() +
2675 ", leaving " + nai.numNetworkRequests() + " requests.");
2676 }
2677 // If there are still lingered requests on this network, don't tear it down,
2678 // but resume lingering instead.
2679 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002680 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002681 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2682 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002683 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002684 wasKept = true;
2685 }
Hugo Benichicd952782017-09-20 11:20:14 +09002686 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002687 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2688 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002689 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002690 }
Erik Klineacdd6392016-07-07 16:50:58 +09002691 }
2692
2693 // TODO: remove this code once we know that the Slog.wtf is never hit.
2694 //
2695 // Find all networks that are satisfying this request and remove the request
2696 // from their request lists.
2697 // TODO - it's my understanding that for a request there is only a single
2698 // network satisfying it, so this loop is wasteful
2699 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2700 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2701 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2702 otherNai.name() + ", but mNetworkAgentInfos says " +
2703 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002704 }
2705 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002706
Erik Klineacdd6392016-07-07 16:50:58 +09002707 // Maintain the illusion. When this request arrived, we might have pretended
2708 // that a network connected to serve it, even though the network was already
2709 // connected. Now that this request has gone away, we might have to pretend
2710 // that the network disconnected. LegacyTypeTracker will generate that
2711 // phantom disconnect for this type.
2712 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2713 boolean doRemove = true;
2714 if (wasKept) {
2715 // check if any of the remaining requests for this network are for the
2716 // same legacy type - if so, don't remove the nai
2717 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2718 NetworkRequest otherRequest = nai.requestAt(i);
2719 if (otherRequest.legacyType == nri.request.legacyType &&
2720 otherRequest.isRequest()) {
2721 if (DBG) log(" still have other legacy request - leaving");
2722 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002723 }
2724 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002725 }
2726
Erik Klineacdd6392016-07-07 16:50:58 +09002727 if (doRemove) {
2728 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002729 }
2730 }
Erik Klineacdd6392016-07-07 16:50:58 +09002731
2732 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2733 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2734 nri.request);
2735 }
2736 } else {
2737 // listens don't have a singular affectedNetwork. Check all networks to see
2738 // if this listen request applies and remove it.
2739 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2740 nai.removeRequest(nri.request.requestId);
2741 if (nri.request.networkCapabilities.hasSignalStrength() &&
2742 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2743 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2744 }
2745 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002746 }
2747 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002748
Lorenzo Colitti18660282016-07-04 12:55:44 +09002749 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002750 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2751 enforceConnectivityInternalPermission();
2752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002753 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002754 }
2755
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002756 @Override
2757 public void setAvoidUnvalidated(Network network) {
2758 enforceConnectivityInternalPermission();
2759 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2760 }
2761
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002762 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2763 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2764 " accept=" + accept + " always=" + always);
2765
2766 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2767 if (nai == null) {
2768 // Nothing to do.
2769 return;
2770 }
2771
2772 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002773 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002774 return;
2775 }
2776
2777 if (!nai.networkMisc.explicitlySelected) {
2778 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2779 }
2780
2781 if (accept != nai.networkMisc.acceptUnvalidated) {
2782 int oldScore = nai.getCurrentScore();
2783 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002784 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002785 sendUpdatedScoreToFactories(nai);
2786 }
2787
2788 if (always) {
2789 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002790 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002791 }
2792
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002793 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002794 // Tell the NetworkAgent to not automatically reconnect to the network.
2795 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2796 // Teardown the nework.
2797 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002798 }
2799
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002800 }
2801
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002802 private void handleSetAvoidUnvalidated(Network network) {
2803 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2804 if (nai == null || nai.lastValidated) {
2805 // Nothing to do. The network either disconnected or revalidated.
2806 return;
2807 }
2808 if (!nai.avoidUnvalidated) {
2809 int oldScore = nai.getCurrentScore();
2810 nai.avoidUnvalidated = true;
2811 rematchAllNetworksAndRequests(nai, oldScore);
2812 sendUpdatedScoreToFactories(nai);
2813 }
2814 }
2815
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002816 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002817 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002818 mHandler.sendMessageDelayed(
2819 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2820 PROMPT_UNVALIDATED_DELAY_MS);
2821 }
2822
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002823 @Override
2824 public void startCaptivePortalApp(Network network) {
2825 enforceConnectivityInternalPermission();
2826 mHandler.post(() -> {
2827 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2828 if (nai == null) return;
2829 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2830 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2831 });
2832 }
2833
Hugo Benichic8e9e122016-09-14 23:23:08 +00002834 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002835 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002836 }
2837
Erik Kline065ab6e2016-10-02 18:02:14 +09002838 private void rematchForAvoidBadWifiUpdate() {
2839 rematchAllNetworksAndRequests(null, 0);
2840 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2841 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2842 sendUpdatedScoreToFactories(nai);
2843 }
2844 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002845 }
2846
Erik Kline065ab6e2016-10-02 18:02:14 +09002847 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002848 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002849 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002850 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002851 if (!configRestrict) {
2852 pw.println("Bad Wi-Fi avoidance: unrestricted");
2853 return;
2854 }
2855
2856 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2857 pw.increaseIndent();
2858 pw.println("Config restrict: " + configRestrict);
2859
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002860 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002861 String description;
2862 // Can't use a switch statement because strings are legal case labels, but null is not.
2863 if ("0".equals(value)) {
2864 description = "get stuck";
2865 } else if (value == null) {
2866 description = "prompt";
2867 } else if ("1".equals(value)) {
2868 description = "avoid";
2869 } else {
2870 description = value + " (?)";
2871 }
2872 pw.println("User setting: " + description);
2873 pw.println("Network overrides:");
2874 pw.increaseIndent();
2875 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2876 if (nai.avoidUnvalidated) {
2877 pw.println(nai.name());
2878 }
2879 }
2880 pw.decreaseIndent();
2881 pw.decreaseIndent();
2882 }
2883
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002884 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2885 final String action;
2886 switch (type) {
2887 case NO_INTERNET:
2888 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2889 break;
2890 case LOST_INTERNET:
2891 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2892 break;
2893 default:
2894 Slog.wtf(TAG, "Unknown notification type " + type);
2895 return;
2896 }
2897
2898 Intent intent = new Intent(action);
2899 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2900 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2901 intent.setClassName("com.android.settings",
2902 "com.android.settings.wifi.WifiNoInternetDialog");
2903
2904 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2905 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2906 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2907 }
2908
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002909 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002910 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002911 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2912
2913 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2914 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002915 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002916 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002917 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2918 return;
2919 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002920 showValidationNotification(nai, NotificationType.NO_INTERNET);
2921 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002922
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002923 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2924 NetworkCapabilities nc = nai.networkCapabilities;
2925 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002926
Erik Kline065ab6e2016-10-02 18:02:14 +09002927 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002928 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002929 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2930 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002931 }
2932
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002933 @Override
2934 public int getMultipathPreference(Network network) {
2935 enforceAccessPermission();
2936
2937 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002938 if (nai != null && nai.networkCapabilities
2939 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002940 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2941 }
2942
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002943 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2944 if (networkPreference != null) {
2945 return networkPreference;
2946 }
2947
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002948 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2949 }
2950
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002951 private class InternalHandler extends Handler {
2952 public InternalHandler(Looper looper) {
2953 super(looper);
2954 }
2955
2956 @Override
2957 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002958 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002959 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002960 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002961 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002962 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002963 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002964 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002965 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002966 break;
2967 }
Jason Monkdecd2952013-10-10 14:02:51 -04002968 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002969 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002970 break;
2971 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002972 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002973 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2974 break;
2975 }
2976 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2977 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002978 break;
2979 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002980 case EVENT_REGISTER_NETWORK_AGENT: {
2981 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2982 break;
2983 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002984 case EVENT_REGISTER_NETWORK_REQUEST:
2985 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002986 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002987 break;
2988 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002989 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2990 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002991 handleRegisterNetworkRequestWithIntent(msg);
2992 break;
2993 }
Erik Kline57faba92015-11-25 12:49:38 +09002994 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2995 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2996 handleTimedOutNetworkRequest(nri);
2997 break;
2998 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002999 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3000 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3001 break;
3002 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003003 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003004 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003005 break;
3006 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003007 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003008 Network network = (Network) msg.obj;
3009 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003010 break;
3011 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003012 case EVENT_SET_AVOID_UNVALIDATED: {
3013 handleSetAvoidUnvalidated((Network) msg.obj);
3014 break;
3015 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003016 case EVENT_PROMPT_UNVALIDATED: {
3017 handlePromptUnvalidated((Network) msg.obj);
3018 break;
3019 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003020 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3021 handleMobileDataAlwaysOn();
3022 break;
3023 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003024 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3025 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3026 mKeepaliveTracker.handleStartKeepalive(msg);
3027 break;
3028 }
3029 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3030 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3031 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3032 int slot = msg.arg1;
3033 int reason = msg.arg2;
3034 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3035 break;
3036 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003037 case EVENT_SYSTEM_READY: {
3038 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3039 nai.networkMonitor.systemReady = true;
3040 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003041 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003042 break;
3043 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003044 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003045 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003046 break;
3047 }
Erik Klinea24d4592018-01-11 21:07:29 +09003048 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3049 handlePrivateDnsSettingsChanged();
3050 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 }
3052 }
3053 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003054
3055 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003056 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003057 public int tether(String iface, String callerPkg) {
3058 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003059 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003060 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003061 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003062 } else {
3063 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3064 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003065 }
3066
3067 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003068 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003069 public int untether(String iface, String callerPkg) {
3070 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003071
3072 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003073 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003074 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003075 } else {
3076 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3077 }
3078 }
3079
3080 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003081 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003082 public int getLastTetherError(String iface) {
3083 enforceTetherAccessPermission();
3084
3085 if (isTetheringSupported()) {
3086 return mTethering.getLastTetherError(iface);
3087 } else {
3088 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3089 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003090 }
3091
3092 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003093 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003094 public String[] getTetherableUsbRegexs() {
3095 enforceTetherAccessPermission();
3096 if (isTetheringSupported()) {
3097 return mTethering.getTetherableUsbRegexs();
3098 } else {
3099 return new String[0];
3100 }
3101 }
3102
Lorenzo Colitti18660282016-07-04 12:55:44 +09003103 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003104 public String[] getTetherableWifiRegexs() {
3105 enforceTetherAccessPermission();
3106 if (isTetheringSupported()) {
3107 return mTethering.getTetherableWifiRegexs();
3108 } else {
3109 return new String[0];
3110 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003111 }
3112
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003114 public String[] getTetherableBluetoothRegexs() {
3115 enforceTetherAccessPermission();
3116 if (isTetheringSupported()) {
3117 return mTethering.getTetherableBluetoothRegexs();
3118 } else {
3119 return new String[0];
3120 }
3121 }
3122
Lorenzo Colitti18660282016-07-04 12:55:44 +09003123 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003124 public int setUsbTethering(boolean enable, String callerPkg) {
3125 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003126 if (isTetheringSupported()) {
3127 return mTethering.setUsbTethering(enable);
3128 } else {
3129 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3130 }
3131 }
3132
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003133 // TODO - move iface listing, queries, etc to new module
3134 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003135 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003136 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003137 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003138 return mTethering.getTetherableIfaces();
3139 }
3140
Lorenzo Colitti18660282016-07-04 12:55:44 +09003141 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003142 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003143 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003144 return mTethering.getTetheredIfaces();
3145 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003146
Lorenzo Colitti18660282016-07-04 12:55:44 +09003147 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003148 public String[] getTetheringErroredIfaces() {
3149 enforceTetherAccessPermission();
3150 return mTethering.getErroredIfaces();
3151 }
3152
Lorenzo Colitti18660282016-07-04 12:55:44 +09003153 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003154 public String[] getTetheredDhcpRanges() {
3155 enforceConnectivityInternalPermission();
3156 return mTethering.getTetheredDhcpRanges();
3157 }
3158
Udam Saini0e94c362017-06-07 12:06:28 -07003159 @Override
3160 public boolean isTetheringSupported(String callerPkg) {
3161 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3162 return isTetheringSupported();
3163 }
3164
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003165 // if ro.tether.denied = true we default to no tethering
3166 // gservices could set the secure setting to 1 though to enable it on a build where it
3167 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003168 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003169 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3170 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3171 Settings.Global.TETHER_SUPPORTED, defaultVal));
3172 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003173 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003174
3175 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3176 boolean adminUser = false;
3177 final long token = Binder.clearCallingIdentity();
3178 try {
3179 adminUser = mUserManager.isAdminUser();
3180 } finally {
3181 Binder.restoreCallingIdentity(token);
3182 }
3183
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003184 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003185 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003186
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003187 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003188 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3189 String callerPkg) {
3190 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003191 if (!isTetheringSupported()) {
3192 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3193 return;
3194 }
3195 mTethering.startTethering(type, receiver, showProvisioningUi);
3196 }
3197
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003198 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003199 public void stopTethering(int type, String callerPkg) {
3200 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003201 mTethering.stopTethering(type);
3202 }
3203
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003204 // Called when we lose the default network and have no replacement yet.
3205 // This will automatically be cleared after X seconds or a new default network
3206 // becomes CONNECTED, whichever happens first. The timer is started by the
3207 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003208 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003209 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003210 if (mNetTransitionWakeLock.isHeld()) {
3211 return;
3212 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003213 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003214 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3215 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003216 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003217 mWakelockLogs.log("ACQUIRE for " + forWhom);
3218 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3219 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003220 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003221
Hugo Benichi4c31b342017-03-30 23:18:10 +09003222 // Called when we gain a new default network to release the network transition wakelock in a
3223 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3224 // message is cancelled.
3225 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003226 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003227 if (!mNetTransitionWakeLock.isHeld()) {
3228 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003229 }
3230 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003231 // Cancel self timeout on wakelock hold.
3232 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3233 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3234 mHandler.sendMessageDelayed(msg, 1000);
3235 }
3236
3237 // Called when either message of ensureNetworkTransitionWakelock or
3238 // scheduleReleaseNetworkTransitionWakelock is processed.
3239 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3240 String event = eventName(eventId);
3241 synchronized (this) {
3242 if (!mNetTransitionWakeLock.isHeld()) {
3243 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3244 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3245 return;
3246 }
3247 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003248 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3249 mTotalWakelockDurationMs += lockDuration;
3250 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3251 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003252 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003253 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003254 }
3255
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003256 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003257 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003258 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003259 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003260 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003261 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003262 }
3263
Lorenzo Colitti18660282016-07-04 12:55:44 +09003264 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003265 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003266 enforceAccessPermission();
3267 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003268 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003269 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003270 mHandler.sendMessage(
3271 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3272 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003273
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003274 private void handleReportNetworkConnectivity(
3275 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003276 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003277 if (network == null) {
3278 nai = getDefaultNetwork();
3279 } else {
3280 nai = getNetworkAgentInfoForNetwork(network);
3281 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003282 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3283 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3284 return;
3285 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003286 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003287 if (hasConnectivity == nai.lastValidated) {
3288 return;
3289 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003290 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003291 int netid = nai.network.netId;
3292 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003293 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003294 // Validating a network that has not yet connected could result in a call to
3295 // rematchNetworkAndRequests() which is not meant to work on such networks.
3296 if (!nai.everConnected) {
3297 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003298 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003299 LinkProperties lp = getLinkProperties(nai);
3300 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3301 return;
3302 }
3303 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003304 }
3305
Paul Jensencee9b512015-05-06 07:32:40 -04003306 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003307 // this information is already available as a world read/writable jvm property
3308 // so this API change wouldn't have a benifit. It also breaks the passing
3309 // of proxy info to all the JVMs.
3310 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003311 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003312 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003313 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3314 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 }
3317
Lorenzo Colitti18660282016-07-04 12:55:44 +09003318 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003319 public ProxyInfo getProxyForNetwork(Network network) {
3320 if (network == null) return getDefaultProxy();
3321 final ProxyInfo globalProxy = getGlobalProxy();
3322 if (globalProxy != null) return globalProxy;
3323 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3324 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3325 // caller may not have.
3326 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3327 if (nai == null) return null;
3328 synchronized (nai) {
3329 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3330 if (proxyInfo == null) return null;
3331 return new ProxyInfo(proxyInfo);
3332 }
3333 }
3334
Paul Jensene0bef712014-12-10 15:12:18 -05003335 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3336 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3337 // proxy is null then there is no proxy in place).
3338 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3339 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3340 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3341 proxy = null;
3342 }
3343 return proxy;
3344 }
3345
3346 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3347 // better for determining if a new proxy broadcast is necessary:
3348 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3349 // avoid unnecessary broadcasts.
3350 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3351 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3352 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3353 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3354 // all set.
3355 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3356 a = canonicalizeProxyInfo(a);
3357 b = canonicalizeProxyInfo(b);
3358 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3359 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3360 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3361 }
3362
Jason Monk207900c2014-04-25 15:00:09 -04003363 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003364 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003365
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003366 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003367 if (proxyProperties == mGlobalProxy) return;
3368 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3369 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3370
3371 String host = "";
3372 int port = 0;
3373 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003374 String pacFileUrl = "";
3375 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003376 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003377 if (!proxyProperties.isValid()) {
3378 if (DBG)
3379 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3380 return;
3381 }
Jason Monk207900c2014-04-25 15:00:09 -04003382 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 host = mGlobalProxy.getHost();
3384 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003385 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003386 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003387 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003388 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003389 } else {
3390 mGlobalProxy = null;
3391 }
3392 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003393 final long token = Binder.clearCallingIdentity();
3394 try {
3395 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3396 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3397 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3398 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003399 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003400 } finally {
3401 Binder.restoreCallingIdentity(token);
3402 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403
Jason Monkcf0f97a2014-10-02 15:39:38 -04003404 if (mGlobalProxy == null) {
3405 proxyProperties = mDefaultProxy;
3406 }
3407 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003409 }
3410
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003411 private void loadGlobalProxy() {
3412 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003413 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3414 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3415 String exclList = Settings.Global.getString(res,
3416 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003417 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3418 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003419 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003420 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003421 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003422 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003423 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003424 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003425 if (!proxyProperties.isValid()) {
3426 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3427 return;
3428 }
3429
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003430 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003431 mGlobalProxy = proxyProperties;
3432 }
3433 }
3434 }
3435
Jason Monk207900c2014-04-25 15:00:09 -04003436 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003437 // this information is already available as a world read/writable jvm property
3438 // so this API change wouldn't have a benifit. It also breaks the passing
3439 // of proxy info to all the JVMs.
3440 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003441 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 return mGlobalProxy;
3443 }
3444 }
3445
Jason Monk207900c2014-04-25 15:00:09 -04003446 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003447 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003448 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003449 proxy = null;
3450 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003451 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003452 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003453 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003454 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003455 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3456 return;
3457 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003458
3459 // This call could be coming from the PacManager, containing the port of the local
3460 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3461 // global (to get the correct local port), and send a broadcast.
3462 // TODO: Switch PacManager to have its own message to send back rather than
3463 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003464 if ((mGlobalProxy != null) && (proxy != null)
3465 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003466 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3467 mGlobalProxy = proxy;
3468 sendProxyBroadcast(mGlobalProxy);
3469 return;
3470 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003471 mDefaultProxy = proxy;
3472
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003473 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003474 if (!mDefaultProxyDisabled) {
3475 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 }
3477 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003478 }
3479
Paul Jensene0bef712014-12-10 15:12:18 -05003480 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3481 // This method gets called when any network changes proxy, but the broadcast only ever contains
3482 // the default proxy (even if it hasn't changed).
3483 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3484 // world where an app might be bound to a non-default network.
3485 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3486 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3487 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3488
3489 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3490 sendProxyBroadcast(getDefaultProxy());
3491 }
3492 }
3493
Robert Greenwalt434203a2010-10-11 16:00:27 -07003494 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003495 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3496 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003497 if (!TextUtils.isEmpty(proxy)) {
3498 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003499 if (data.length == 0) {
3500 return;
3501 }
3502
Robert Greenwalt434203a2010-10-11 16:00:27 -07003503 String proxyHost = data[0];
3504 int proxyPort = 8080;
3505 if (data.length > 1) {
3506 try {
3507 proxyPort = Integer.parseInt(data[1]);
3508 } catch (NumberFormatException e) {
3509 return;
3510 }
3511 }
Jason Monk207900c2014-04-25 15:00:09 -04003512 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003513 setGlobalProxy(p);
3514 }
3515 }
3516
Jason Monk207900c2014-04-25 15:00:09 -04003517 private void sendProxyBroadcast(ProxyInfo proxy) {
3518 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003519 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003520 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003521 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003522 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3523 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003524 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003525 final long ident = Binder.clearCallingIdentity();
3526 try {
3527 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3528 } finally {
3529 Binder.restoreCallingIdentity(ident);
3530 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 }
3532
3533 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003534 final private HashMap<Uri, Integer> mUriEventMap;
3535 final private Context mContext;
3536 final private Handler mHandler;
3537
3538 SettingsObserver(Context context, Handler handler) {
3539 super(null);
3540 mUriEventMap = new HashMap<Uri, Integer>();
3541 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003542 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003543 }
3544
Erik Klineda4bfa82015-04-30 12:58:40 +09003545 void observe(Uri uri, int what) {
3546 mUriEventMap.put(uri, what);
3547 final ContentResolver resolver = mContext.getContentResolver();
3548 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003549 }
3550
3551 @Override
3552 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003553 Slog.wtf(TAG, "Should never be reached.");
3554 }
3555
3556 @Override
3557 public void onChange(boolean selfChange, Uri uri) {
3558 final Integer what = mUriEventMap.get(uri);
3559 if (what != null) {
3560 mHandler.obtainMessage(what.intValue()).sendToTarget();
3561 } else {
3562 loge("No matching event to send for URI=" + uri);
3563 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003564 }
3565 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003566
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003567 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003568 Slog.d(TAG, s);
3569 }
3570
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003571 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003572 Slog.e(TAG, s);
3573 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003574
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003575 private static void loge(String s, Throwable t) {
3576 Slog.e(TAG, s, t);
3577 }
3578
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003579 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003580 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003581 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3582 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3583 *
3584 * @param oldPackage Package name of the application which currently controls VPN, which will
3585 * be replaced. If there is no such application, this should should either be
3586 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3587 * @param newPackage Package name of the application which should gain control of VPN, or
3588 * {@code null} to disable.
3589 * @param userId User for whom to prepare the new VPN.
3590 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003591 * @hide
3592 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003593 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003594 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3595 int userId) {
3596 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003597
Hugo Benichi20035e02017-04-26 14:53:28 +09003598 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003599 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003600 Vpn vpn = mVpns.get(userId);
3601 if (vpn != null) {
3602 return vpn.prepare(oldPackage, newPackage);
3603 } else {
3604 return false;
3605 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003606 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003607 }
3608
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003609 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003610 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3611 * This method is used by system-privileged apps.
3612 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3613 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3614 *
3615 * @param packageName The package for which authorization state should change.
3616 * @param userId User for whom {@code packageName} is installed.
3617 * @param authorized {@code true} if this app should be able to start a VPN connection without
3618 * explicit user approval, {@code false} if not.
3619 *
Jeff Davidson05542602014-08-11 14:07:27 -07003620 * @hide
3621 */
3622 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003623 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3624 enforceCrossUserPermission(userId);
3625
Hugo Benichi20035e02017-04-26 14:53:28 +09003626 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003627 Vpn vpn = mVpns.get(userId);
3628 if (vpn != null) {
3629 vpn.setPackageAuthorization(packageName, authorized);
3630 }
Jeff Davidson05542602014-08-11 14:07:27 -07003631 }
3632 }
3633
3634 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003635 * Configure a TUN interface and return its file descriptor. Parameters
3636 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003637 * and not available in ConnectivityManager. Permissions are checked in
3638 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003639 * @hide
3640 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003641 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003642 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003644 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003645 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003646 return mVpns.get(user).establish(config);
3647 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003648 }
3649
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003650 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003651 * Start legacy VPN, controlling native daemons as needed. Creates a
3652 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003653 */
3654 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003655 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003656 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003657 final LinkProperties egress = getActiveLinkProperties();
3658 if (egress == null) {
3659 throw new IllegalStateException("Missing active network connection");
3660 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003661 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003662 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003663 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3664 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003665 }
3666
3667 /**
3668 * Return the information of the ongoing legacy VPN. This method is used
3669 * by VpnSettings and not available in ConnectivityManager. Permissions
3670 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003671 */
3672 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003673 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3674 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003675
Hugo Benichi20035e02017-04-26 14:53:28 +09003676 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003677 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003678 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003679 }
3680
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003681 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003682 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3683 * and not available in ConnectivityManager.
3684 */
3685 @Override
3686 public VpnInfo[] getAllVpnInfo() {
3687 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003688 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003689 if (mLockdownEnabled) {
3690 return new VpnInfo[0];
3691 }
3692
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003693 List<VpnInfo> infoList = new ArrayList<>();
3694 for (int i = 0; i < mVpns.size(); i++) {
3695 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3696 if (info != null) {
3697 infoList.add(info);
3698 }
3699 }
3700 return infoList.toArray(new VpnInfo[infoList.size()]);
3701 }
3702 }
3703
3704 /**
3705 * @return VPN information for accounting, or null if we can't retrieve all required
3706 * information, e.g primary underlying iface.
3707 */
3708 @Nullable
3709 private VpnInfo createVpnInfo(Vpn vpn) {
3710 VpnInfo info = vpn.getVpnInfo();
3711 if (info == null) {
3712 return null;
3713 }
3714 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3715 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3716 // the underlyingNetworks list.
3717 if (underlyingNetworks == null) {
3718 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3719 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3720 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3721 }
3722 } else if (underlyingNetworks.length > 0) {
3723 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3724 if (linkProperties != null) {
3725 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3726 }
3727 }
3728 return info.primaryUnderlyingIface == null ? null : info;
3729 }
3730
3731 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003732 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3733 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003734 * Permissions are checked in Vpn class.
3735 * @hide
3736 */
3737 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003738 public VpnConfig getVpnConfig(int userId) {
3739 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003740 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003741 Vpn vpn = mVpns.get(userId);
3742 if (vpn != null) {
3743 return vpn.getVpnConfig();
3744 } else {
3745 return null;
3746 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003747 }
3748 }
3749
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003750 @Override
3751 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003752 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3753 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3754 return false;
3755 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003756
Hugo Benichi69744342017-11-27 10:57:16 +09003757 synchronized (mVpns) {
3758 // Tear down existing lockdown if profile was removed
3759 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3760 if (mLockdownEnabled) {
3761 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3762 if (profileTag == null) {
3763 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3764 return false;
3765 }
3766 String profileName = new String(profileTag);
3767 final VpnProfile profile = VpnProfile.decode(
3768 profileName, mKeyStore.get(Credentials.VPN + profileName));
3769 if (profile == null) {
3770 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3771 setLockdownTracker(null);
3772 return true;
3773 }
3774 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003775 Vpn vpn = mVpns.get(user);
3776 if (vpn == null) {
3777 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3778 return false;
3779 }
3780 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003781 } else {
3782 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003783 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003784 }
3785
3786 return true;
3787 }
3788
3789 /**
3790 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3791 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3792 */
Hugo Benichi69744342017-11-27 10:57:16 +09003793 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003794 private void setLockdownTracker(LockdownVpnTracker tracker) {
3795 // Shutdown any existing tracker
3796 final LockdownVpnTracker existing = mLockdownTracker;
3797 mLockdownTracker = null;
3798 if (existing != null) {
3799 existing.shutdown();
3800 }
3801
Robin Leec3736bc2017-03-10 16:19:54 +00003802 if (tracker != null) {
3803 mLockdownTracker = tracker;
3804 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003805 }
3806 }
3807
Hugo Benichi69744342017-11-27 10:57:16 +09003808 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003809 private void throwIfLockdownEnabled() {
3810 if (mLockdownEnabled) {
3811 throw new IllegalStateException("Unavailable in lockdown mode");
3812 }
3813 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003814
Robin Lee244ce8e2016-01-05 18:03:46 +00003815 /**
Robin Lee17e61832016-05-09 13:46:28 +01003816 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3817 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003818 *
Robin Lee17e61832016-05-09 13:46:28 +01003819 * @return {@code true} if the service was started, the service was already connected, or there
3820 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003821 */
Robin Lee17e61832016-05-09 13:46:28 +01003822 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003823 synchronized (mVpns) {
3824 Vpn vpn = mVpns.get(userId);
3825 if (vpn == null) {
3826 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3827 // exists already.
3828 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3829 return false;
3830 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003831
Robin Lee812800c2016-05-13 15:38:08 +01003832 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003833 }
3834 }
3835
3836 @Override
Charles He36738632017-05-15 17:07:18 +01003837 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3838 enforceSettingsPermission();
3839 enforceCrossUserPermission(userId);
3840
3841 synchronized (mVpns) {
3842 Vpn vpn = mVpns.get(userId);
3843 if (vpn == null) {
3844 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3845 return false;
3846 }
3847 return vpn.isAlwaysOnPackageSupported(packageName);
3848 }
3849 }
3850
3851 @Override
Robin Leedc679712016-05-03 13:23:03 +01003852 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003853 enforceConnectivityInternalPermission();
3854 enforceCrossUserPermission(userId);
3855
Robin Lee244ce8e2016-01-05 18:03:46 +00003856 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003857 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3858 if (LockdownVpnTracker.isEnabled()) {
3859 return false;
3860 }
3861
Robin Lee244ce8e2016-01-05 18:03:46 +00003862 Vpn vpn = mVpns.get(userId);
3863 if (vpn == null) {
3864 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3865 return false;
3866 }
Robin Lee17e61832016-05-09 13:46:28 +01003867 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003868 return false;
3869 }
Robin Lee17e61832016-05-09 13:46:28 +01003870 if (!startAlwaysOnVpn(userId)) {
3871 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003872 return false;
3873 }
3874 }
3875 return true;
3876 }
3877
3878 @Override
3879 public String getAlwaysOnVpnPackage(int userId) {
3880 enforceConnectivityInternalPermission();
3881 enforceCrossUserPermission(userId);
3882
3883 synchronized (mVpns) {
3884 Vpn vpn = mVpns.get(userId);
3885 if (vpn == null) {
3886 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3887 return null;
3888 }
3889 return vpn.getAlwaysOnPackage();
3890 }
3891 }
3892
Wink Savilleab9321d2013-06-29 21:10:57 -07003893 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003894 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003895 // TODO: Remove? Any reason to trigger a provisioning check?
3896 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003897 }
3898
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003899 /** Location to an updatable file listing carrier provisioning urls.
3900 * An example:
3901 *
3902 * <?xml version="1.0" encoding="utf-8"?>
3903 * <provisioningUrls>
3904 * <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 -07003905 * </provisioningUrls>
3906 */
3907 private static final String PROVISIONING_URL_PATH =
3908 "/data/misc/radio/provisioning_urls.xml";
3909 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003910
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003911 /** XML tag for root element. */
3912 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3913 /** XML tag for individual url */
3914 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003915 /** XML attribute for mcc */
3916 private static final String ATTR_MCC = "mcc";
3917 /** XML attribute for mnc */
3918 private static final String ATTR_MNC = "mnc";
3919
Paul Jensen434dde82015-06-11 09:43:30 -04003920 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003921 FileReader fileReader = null;
3922 XmlPullParser parser = null;
3923 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003924
3925 try {
3926 fileReader = new FileReader(mProvisioningUrlFile);
3927 parser = Xml.newPullParser();
3928 parser.setInput(fileReader);
3929 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3930
3931 while (true) {
3932 XmlUtils.nextElement(parser);
3933
3934 String element = parser.getName();
3935 if (element == null) break;
3936
Paul Jensen434dde82015-06-11 09:43:30 -04003937 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003938 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3939 try {
3940 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3941 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3942 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3943 parser.next();
3944 if (parser.getEventType() == XmlPullParser.TEXT) {
3945 return parser.getText();
3946 }
3947 }
3948 }
3949 } catch (NumberFormatException e) {
3950 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3951 }
3952 }
3953 }
3954 return null;
3955 } catch (FileNotFoundException e) {
3956 loge("Carrier Provisioning Urls file not found");
3957 } catch (XmlPullParserException e) {
3958 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3959 } catch (IOException e) {
3960 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3961 } finally {
3962 if (fileReader != null) {
3963 try {
3964 fileReader.close();
3965 } catch (IOException e) {}
3966 }
3967 }
3968 return null;
3969 }
3970
Wink Saville42d4f082013-07-20 20:31:59 -07003971 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003972 public String getMobileProvisioningUrl() {
3973 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003974 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003975 if (TextUtils.isEmpty(url)) {
3976 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003977 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003978 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003979 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003980 }
Wink Saville8cf35602013-07-10 23:00:07 -07003981 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003982 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003983 String phoneNumber = mTelephonyManager.getLine1Number();
3984 if (TextUtils.isEmpty(phoneNumber)) {
3985 phoneNumber = "0000000000";
3986 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003987 url = String.format(url,
3988 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3989 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003990 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003991 }
3992
Wink Savilleab9321d2013-06-29 21:10:57 -07003993 return url;
3994 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003995
Wink Saville948282b2013-08-29 08:55:16 -07003996 @Override
3997 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003998 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003999 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004000 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4001 return;
4002 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004003 final long ident = Binder.clearCallingIdentity();
4004 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004005 // Concatenate the range of types onto the range of NetIDs.
4006 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4007 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004008 } finally {
4009 Binder.restoreCallingIdentity(ident);
4010 }
Wink Saville948282b2013-08-29 08:55:16 -07004011 }
Wink Saville7788c612013-08-29 14:57:08 -07004012
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004013 @Override
4014 public void setAirplaneMode(boolean enable) {
4015 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004016 final long ident = Binder.clearCallingIdentity();
4017 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004018 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004019 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004020 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4021 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004022 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004023 } finally {
4024 Binder.restoreCallingIdentity(ident);
4025 }
4026 }
4027
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004028 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004029 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004030 Vpn userVpn = mVpns.get(userId);
4031 if (userVpn != null) {
4032 loge("Starting user already has a VPN");
4033 return;
4034 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004035 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004036 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004037 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4038 updateLockdownVpn();
4039 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004040 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004041 }
4042
4043 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004044 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004045 Vpn userVpn = mVpns.get(userId);
4046 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004047 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004048 return;
4049 }
Robin Lee17e61832016-05-09 13:46:28 +01004050 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004051 mVpns.delete(userId);
4052 }
4053 }
4054
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004055 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004056 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004057 final int vpnsSize = mVpns.size();
4058 for (int i = 0; i < vpnsSize; i++) {
4059 Vpn vpn = mVpns.valueAt(i);
4060 vpn.onUserAdded(userId);
4061 }
4062 }
4063 }
4064
4065 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004066 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004067 final int vpnsSize = mVpns.size();
4068 for (int i = 0; i < vpnsSize; i++) {
4069 Vpn vpn = mVpns.valueAt(i);
4070 vpn.onUserRemoved(userId);
4071 }
4072 }
4073 }
4074
Robin Lee89e7a692016-02-29 14:38:17 +00004075 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004076 synchronized (mVpns) {
4077 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4078 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4079 updateLockdownVpn();
4080 } else {
4081 startAlwaysOnVpn(userId);
4082 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004083 }
4084 }
4085
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004086 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4087 @Override
4088 public void onReceive(Context context, Intent intent) {
4089 final String action = intent.getAction();
4090 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4091 if (userId == UserHandle.USER_NULL) return;
4092
Robin Lee323f29d2016-05-04 16:38:06 +01004093 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004094 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004095 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004096 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004097 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4098 onUserAdded(userId);
4099 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4100 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004101 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4102 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004103 }
4104 }
4105 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004106
Robin Lee95204e02017-01-27 11:59:22 +00004107 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4108 @Override
4109 public void onReceive(Context context, Intent intent) {
4110 // Try creating lockdown tracker, since user present usually means
4111 // unlocked keystore.
4112 updateLockdownVpn();
4113 mContext.unregisterReceiver(this);
4114 }
4115 };
4116
Robert Greenwalta67be032014-05-16 15:49:14 -07004117 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4118 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4120 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004121
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004122 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4123 // Map from UID to number of NetworkRequests that UID has filed.
4124 @GuardedBy("mUidToNetworkRequestCount")
4125 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4126
Robert Greenwalta67be032014-05-16 15:49:14 -07004127 private static class NetworkFactoryInfo {
4128 public final String name;
4129 public final Messenger messenger;
4130 public final AsyncChannel asyncChannel;
4131
4132 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4133 this.name = name;
4134 this.messenger = messenger;
4135 this.asyncChannel = asyncChannel;
4136 }
4137 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004138
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004139 private void ensureNetworkRequestHasType(NetworkRequest request) {
4140 if (request.type == NetworkRequest.Type.NONE) {
4141 throw new IllegalArgumentException(
4142 "All NetworkRequests in ConnectivityService must have a type");
4143 }
4144 }
4145
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004146 /**
4147 * Tracks info about the requester.
4148 * Also used to notice when the calling process dies so we can self-expire
4149 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004152 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004153 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 final int mPid;
4156 final int mUid;
4157 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004159 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004160 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004161 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004162 mPendingIntent = pi;
4163 messenger = null;
4164 mBinder = null;
4165 mPid = getCallingPid();
4166 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004167 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168 }
4169
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004170 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 super();
4172 messenger = m;
4173 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004174 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 mBinder = binder;
4176 mPid = getCallingPid();
4177 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004179 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180
4181 try {
4182 mBinder.linkToDeath(this, 0);
4183 } catch (RemoteException e) {
4184 binderDied();
4185 }
4186 }
4187
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004188 private void enforceRequestCountLimit() {
4189 synchronized (mUidToNetworkRequestCount) {
4190 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4191 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004192 throw new ServiceSpecificException(
4193 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004194 }
4195 mUidToNetworkRequestCount.put(mUid, networkRequests);
4196 }
4197 }
4198
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 if (mBinder != null) {
4201 mBinder.unlinkToDeath(this, 0);
4202 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004203 }
4204
4205 public void binderDied() {
4206 log("ConnectivityService NetworkRequestInfo binderDied(" +
4207 request + ", " + mBinder + ")");
4208 releaseNetworkRequest(request);
4209 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004210
4211 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004212 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004214 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004215 }
4216
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004217 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4218 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4219 if (badCapability != null) {
4220 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004221 }
4222 }
4223
Erik Kline9d598e12015-07-13 16:37:51 +09004224 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004225 final SortedSet<Integer> thresholds = new TreeSet();
4226 synchronized (nai) {
4227 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4228 if (nri.request.networkCapabilities.hasSignalStrength() &&
4229 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4230 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4231 }
4232 }
4233 }
Erik Kline9d598e12015-07-13 16:37:51 +09004234 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004235 }
4236
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004237 private void updateSignalStrengthThresholds(
4238 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4239 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004240 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004241 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4242
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004243 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004244 String detail;
4245 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4246 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4247 } else {
4248 detail = reason;
4249 }
4250 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4251 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4252 }
4253
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004254 nai.asyncChannel.sendMessage(
4255 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004256 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004257 }
4258
Etan Cohen859748f2017-04-03 17:42:34 -07004259 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4260 if (nc == null) {
4261 return;
4262 }
4263 NetworkSpecifier ns = nc.getNetworkSpecifier();
4264 if (ns == null) {
4265 return;
4266 }
4267 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4268 ns.assertValidFromUid(Binder.getCallingUid());
4269 }
4270
Robert Greenwalt9258c642014-03-26 16:47:06 -07004271 @Override
4272 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004273 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004274 final NetworkRequest.Type type = (networkCapabilities == null)
4275 ? NetworkRequest.Type.TRACK_DEFAULT
4276 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004277 // If the requested networkCapabilities is null, take them instead from
4278 // the default network request. This allows callers to keep track of
4279 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004280 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004281 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004282 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004283 enforceAccessPermission();
4284 } else {
4285 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4286 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004287 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4288 // of the app when the request is filed, but we never change the request if the app
4289 // changes network state. http://b/29964605
4290 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004291 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004292 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004293 // Set the UID range for this request to the single UID of the requester, or to an empty
4294 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004295 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4296 // are no visible methods to set the UIDs, an app could use reflection to try and get
4297 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004298 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004299
Etan Cohenba07c8c2017-02-05 10:42:27 -08004300 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301 throw new IllegalArgumentException("Bad timeout specified");
4302 }
Etan Cohen859748f2017-04-03 17:42:34 -07004303 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004304
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004305 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004306 nextNetworkRequestId(), type);
4307 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004308 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004309
4310 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004311 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004312 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004313 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314 }
4315 return networkRequest;
4316 }
4317
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004318 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004319 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004320 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004321 } else {
4322 enforceChangePermission();
4323 }
4324 }
4325
fenglub15e72b2015-03-20 11:29:56 -07004326 @Override
fengludb571472015-04-21 17:12:05 -07004327 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004328 enforceAccessPermission();
4329 NetworkAgentInfo nai = null;
4330 if (network == null) {
4331 return false;
4332 }
4333 synchronized (mNetworkForNetId) {
4334 nai = mNetworkForNetId.get(network.netId);
4335 }
4336 if (nai != null) {
4337 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4338 return true;
4339 }
4340 return false;
4341 }
4342
Felipe Lemeee27cab2016-06-20 16:36:29 -07004343 private boolean isSystem(int uid) {
4344 return uid < Process.FIRST_APPLICATION_UID;
4345 }
fenglub15e72b2015-03-20 11:29:56 -07004346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004347 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004348 final int uid = Binder.getCallingUid();
4349 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004350 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004351 return;
4352 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004353 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4354 // Policy already enforced.
4355 return;
4356 }
4357 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4358 // If UID is restricted, don't allow them to bring up metered APNs.
4359 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004360 }
4361 }
4362
Robert Greenwalt9258c642014-03-26 16:47:06 -07004363 @Override
4364 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4365 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004366 checkNotNull(operation, "PendingIntent cannot be null.");
4367 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4368 enforceNetworkRequestPermissions(networkCapabilities);
4369 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004370 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004371 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004372 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004373
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004374 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004375 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4376 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004377 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004378 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4379 nri));
4380 return networkRequest;
4381 }
4382
Jeremy Joslin79294842014-12-03 17:15:28 -08004383 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4384 mHandler.sendMessageDelayed(
4385 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4386 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4387 }
4388
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004389 @Override
4390 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004391 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4393 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004394 }
4395
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004396 // In order to implement the compatibility measure for pre-M apps that call
4397 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4398 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4399 // This ensures it has permission to do so.
4400 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4401 if (nc == null) {
4402 return false;
4403 }
4404 int[] transportTypes = nc.getTransportTypes();
4405 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4406 return false;
4407 }
4408 try {
4409 mContext.enforceCallingOrSelfPermission(
4410 android.Manifest.permission.ACCESS_WIFI_STATE,
4411 "ConnectivityService");
4412 } catch (SecurityException e) {
4413 return false;
4414 }
4415 return true;
4416 }
4417
Robert Greenwalt9258c642014-03-26 16:47:06 -07004418 @Override
4419 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4420 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004421 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4422 enforceAccessPermission();
4423 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004425 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004426 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004427 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4428 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4429 // onLost and onAvailable callbacks when networks move in and out of the background.
4430 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4431 // can't request networks.
4432 restrictBackgroundRequestForCaller(nc);
4433 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004434
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004435 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004436 NetworkRequest.Type.LISTEN);
4437 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004438 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004439
4440 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4441 return networkRequest;
4442 }
4443
4444 @Override
4445 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4446 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004447 checkNotNull(operation, "PendingIntent cannot be null.");
4448 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4449 enforceAccessPermission();
4450 }
Etan Cohen859748f2017-04-03 17:42:34 -07004451 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004452
Chalard Jeandda156a2018-01-10 21:19:32 +09004453 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004454 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004455
4456 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004457 NetworkRequest.Type.LISTEN);
4458 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004459 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004460
4461 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004462 }
4463
Erik Klineacdd6392016-07-07 16:50:58 +09004464 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004465 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004466 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004467 mHandler.sendMessage(mHandler.obtainMessage(
4468 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004469 }
4470
4471 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004472 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004473 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004474 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4475 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004476 }
4477
Robert Greenwalta67be032014-05-16 15:49:14 -07004478 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004479 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004480 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4481 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4482 }
4483
4484 @Override
4485 public void unregisterNetworkFactory(Messenger messenger) {
4486 enforceConnectivityInternalPermission();
4487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4488 }
4489
4490 private void handleUnregisterNetworkFactory(Messenger messenger) {
4491 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4492 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004493 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004494 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004495 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004496 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004497 }
4498
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 /**
4500 * NetworkAgentInfo supporting a request by requestId.
4501 * These have already been vetted (their Capabilities satisfy the request)
4502 * and the are the highest scored network available.
4503 * the are keyed off the Requests requestId.
4504 */
Hugo Benichicd952782017-09-20 11:20:14 +09004505 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4506 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004507 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4508 new SparseArray<NetworkAgentInfo>();
4509
Paul Jensen31a94f42015-02-13 14:18:39 -05004510 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4511 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4513 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004514 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4515 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4516 // there may not be a strict 1:1 correlation between the two.
4517 @GuardedBy("mNetworkForNetId")
4518 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 // NetworkAgentInfo keyed off its connecting messenger
4521 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004522 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4524 new HashMap<Messenger, NetworkAgentInfo>();
4525
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004526 @GuardedBy("mBlockedAppUids")
4527 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4528
Paul Jensen2c311d62014-11-17 12:34:51 -05004529 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 private final NetworkRequest mDefaultRequest;
4531
Erik Klineda4bfa82015-04-30 12:58:40 +09004532 // Request used to optionally keep mobile data active even when higher
4533 // priority networks like Wi-Fi are active.
4534 private final NetworkRequest mDefaultMobileDataRequest;
4535
Hugo Benichicd952782017-09-20 11:20:14 +09004536 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4537 synchronized (mNetworkForRequestId) {
4538 return mNetworkForRequestId.get(requestId);
4539 }
4540 }
4541
4542 private void clearNetworkForRequest(int requestId) {
4543 synchronized (mNetworkForRequestId) {
4544 mNetworkForRequestId.remove(requestId);
4545 }
4546 }
4547
4548 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4549 synchronized (mNetworkForRequestId) {
4550 mNetworkForRequestId.put(requestId, nai);
4551 }
4552 }
4553
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004554 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004555 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004556 }
4557
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004558 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004559 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004560 }
4561
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004562 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4563 return nri.request.requestId == mDefaultRequest.requestId;
4564 }
4565
Paul Jensen31a94f42015-02-13 14:18:39 -05004566 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004568 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 enforceConnectivityInternalPermission();
4570
Rubin Xu1bb5c082017-09-05 18:40:49 +01004571 LinkProperties lp = new LinkProperties(linkProperties);
4572 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004573 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4574 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004575 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004576 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004577 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004578 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004579 // Make sure the network capabilities reflect what the agent info says.
4580 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004581 synchronized (this) {
4582 nai.networkMonitor.systemReady = mSystemReady;
4583 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004584 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4585 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004586 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004588 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004589 }
4590
Erik Klinee5dac902018-03-04 21:01:01 +09004591 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004592 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004593 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004594 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004595 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004596 }
Erik Klinee5dac902018-03-04 21:01:01 +09004597 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4598 NetworkInfo networkInfo = nai.networkInfo;
4599 nai.networkInfo = null;
4600 updateNetworkInfo(nai, networkInfo);
4601 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004602 }
4603
4604 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4605 LinkProperties newLp = networkAgent.linkProperties;
4606 int netId = networkAgent.network.netId;
4607
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004608 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4609 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004610 if (networkAgent.clatd != null) {
4611 networkAgent.clatd.fixupLinkProperties(oldLp);
4612 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004613
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004614 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004615 updateMtu(newLp, oldLp);
4616 // TODO - figure out what to do for clat
4617// for (LinkProperties lp : newLp.getStackedLinks()) {
4618// updateMtu(lp, null);
4619// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004620 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004621
Erik Kline94887872016-04-05 13:30:49 +09004622 updateRoutes(newLp, oldLp, netId);
4623 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004624
Hugo Benichi6f62b732017-06-27 15:13:20 +09004625 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004626 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004627 if (isDefaultNetwork(networkAgent)) {
4628 handleApplyDefaultProxy(newLp.getHttpProxy());
4629 } else {
4630 updateProxy(newLp, oldLp, networkAgent);
4631 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004632 // TODO - move this check to cover the whole function
4633 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004634 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004635 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4636 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004637
4638 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004639 }
4640
Joel Scherpelz668370b2017-06-08 15:35:21 +09004641 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004642 // Marks are only available on WiFi interaces. Checking for
4643 // marks on unsupported interfaces is harmless.
4644 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4645 return;
4646 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004647
Joel Scherpelz668370b2017-06-08 15:35:21 +09004648 int mark = mContext.getResources().getInteger(
4649 com.android.internal.R.integer.config_networkWakeupPacketMark);
4650 int mask = mContext.getResources().getInteger(
4651 com.android.internal.R.integer.config_networkWakeupPacketMask);
4652
4653 // Mask/mark of zero will not detect anything interesting.
4654 // Don't install rules unless both values are nonzero.
4655 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004656 return;
4657 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004658
4659 final String prefix = "iface:" + iface;
4660 try {
4661 if (add) {
4662 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4663 } else {
4664 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4665 }
4666 } catch (Exception e) {
4667 loge("Exception modifying wakeup packet monitoring: " + e);
4668 }
4669
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004670 }
4671
4672 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4673 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004674 CompareResult<String> interfaceDiff = new CompareResult<String>(
4675 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4676 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004677 for (String iface : interfaceDiff.added) {
4678 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004679 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004680 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004681 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004682 } catch (Exception e) {
4683 loge("Exception adding interface: " + e);
4684 }
4685 }
4686 for (String iface : interfaceDiff.removed) {
4687 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004688 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004689 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004690 mNetd.removeInterfaceFromNetwork(iface, netId);
4691 } catch (Exception e) {
4692 loge("Exception removing interface: " + e);
4693 }
4694 }
4695 }
4696
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004697 /**
4698 * Have netd update routes from oldLp to newLp.
4699 * @return true if routes changed between oldLp and newLp
4700 */
4701 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004702 // Compare the route diff to determine which routes should be added and removed.
4703 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4704 oldLp != null ? oldLp.getAllRoutes() : null,
4705 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004706
4707 // add routes before removing old in case it helps with continuous connectivity
4708
4709 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4710 for (RouteInfo route : routeDiff.added) {
4711 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004712 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 try {
4714 mNetd.addRoute(netId, route);
4715 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004716 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4717 loge("Exception in addRoute for non-gateway: " + e);
4718 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004719 }
4720 }
4721 for (RouteInfo route : routeDiff.added) {
4722 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004723 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004724 try {
4725 mNetd.addRoute(netId, route);
4726 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004727 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4728 loge("Exception in addRoute for gateway: " + e);
4729 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730 }
4731 }
4732
4733 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004734 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004735 try {
4736 mNetd.removeRoute(netId, route);
4737 } catch (Exception e) {
4738 loge("Exception in removeRoute: " + e);
4739 }
4740 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004741 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004742 }
Erik Kline41368502015-06-17 13:19:54 +09004743
Erik Kline94887872016-04-05 13:30:49 +09004744 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4745 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4746 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004747 }
Erik Kline94887872016-04-05 13:30:49 +09004748
Erik Kline1742fe12017-12-13 19:40:49 +09004749 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4750 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4751
Erik Klinea24d4592018-01-11 21:07:29 +09004752 if (DBG) {
4753 final Collection<InetAddress> dnses = newLp.getDnsServers();
4754 log("Setting DNS servers for network " + netId + " to " + dnses);
4755 }
Erik Kline94887872016-04-05 13:30:49 +09004756 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004757 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004758 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004759 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004760 }
Erik Kline4edba012017-04-07 15:29:29 +09004761 }
4762
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004763 private String getNetworkPermission(NetworkCapabilities nc) {
4764 // TODO: make these permission strings AIDL constants instead.
4765 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4766 return NetworkManagementService.PERMISSION_SYSTEM;
4767 }
4768 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4769 return NetworkManagementService.PERMISSION_NETWORK;
4770 }
4771 return null;
4772 }
4773
Paul Jensen3d194ea2015-06-16 14:27:36 -04004774 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004775 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4776 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4777 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004778 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004779 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004780 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004781 if (nai.everConnected &&
4782 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4783 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004784 // does not cause any request (that is not a listen) currently matching that agent to
4785 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004786 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004787 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004788 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004789 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004790 }
4791
Paul Jensen3d194ea2015-06-16 14:27:36 -04004792 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004793 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004794 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004795 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004796 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004797 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004798 }
Paul Jensene0988542015-06-25 15:30:08 -04004799 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004800 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004801 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004802 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004803 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004804 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004805 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004806 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004807 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004808 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004809 if (nai.isSuspended()) {
4810 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4811 } else {
4812 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4813 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004814
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004815 return newNc;
4816 }
4817
4818 /**
4819 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4820 *
4821 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4822 * capabilities we manage and store in {@code nai}, such as validated status and captive
4823 * portal status)
4824 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4825 * potentially triggers rematches.
4826 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4827 * change.)
4828 *
4829 * @param oldScore score of the network before any of the changes that prompted us
4830 * to call this function.
4831 * @param nai the network having its capabilities updated.
4832 * @param nc the new network capabilities.
4833 */
4834 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4835 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4836
4837 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004838
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004839 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004840 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004841 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004842 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004843 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004844 } catch (RemoteException e) {
4845 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004846 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004847 }
4848
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004849 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004850 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004851 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004852 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004853 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004854
Chalard Jeanf213ca12018-01-16 18:43:05 +09004855 updateUids(nai, prevNc, newNc);
4856
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004857 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004858 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4859 // the change we're processing can't affect any requests, it can only affect the listens
4860 // on this network. We might have been called by rematchNetworkAndRequests when a
4861 // network changed foreground state.
4862 processListenRequests(nai, true);
4863 } else {
4864 // If the requestable capabilities have changed or the score changed, we can't have been
4865 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004866 rematchAllNetworksAndRequests(nai, oldScore);
4867 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004868 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004869
4870 // Report changes that are interesting for network statistics tracking.
4871 if (prevNc != null) {
4872 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004873 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004874 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004875 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004876 if (meteredChanged || roamingChanged) {
4877 notifyIfacesChangedForNetworkStats();
4878 }
4879 }
4880
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004881 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004882 // Tell VPNs about updated capabilities, since they may need to
4883 // bubble those changes through.
4884 synchronized (mVpns) {
4885 for (int i = 0; i < mVpns.size(); i++) {
4886 final Vpn vpn = mVpns.valueAt(i);
4887 vpn.updateCapabilities();
4888 }
4889 }
4890 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891 }
4892
Chalard Jeanf213ca12018-01-16 18:43:05 +09004893 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4894 NetworkCapabilities newNc) {
4895 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4896 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4897 if (null == prevRanges) prevRanges = new ArraySet<>();
4898 if (null == newRanges) newRanges = new ArraySet<>();
4899 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4900
4901 prevRanges.removeAll(newRanges);
4902 newRanges.removeAll(prevRangesCopy);
4903
4904 try {
4905 if (!newRanges.isEmpty()) {
4906 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4907 newRanges.toArray(addedRangesArray);
4908 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4909 }
4910 if (!prevRanges.isEmpty()) {
4911 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4912 prevRanges.toArray(removedRangesArray);
4913 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4914 }
4915 } catch (Exception e) {
4916 // Never crash!
4917 loge("Exception in updateUids: " + e);
4918 }
4919 }
4920
Hugo Benichief502882017-09-01 01:23:32 +00004921 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4922 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4923 // Ignore updates for disconnected networks
4924 return;
4925 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004926 // newLp is already a defensive copy.
4927 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004928 if (VDBG) {
4929 log("Update of LinkProperties for " + nai.name() +
4930 "; created=" + nai.created +
4931 "; everConnected=" + nai.everConnected);
4932 }
4933 LinkProperties oldLp = nai.linkProperties;
4934 synchronized (nai) {
4935 nai.linkProperties = newLp;
4936 }
4937 if (nai.everConnected) {
4938 updateLinkProperties(nai, oldLp);
4939 }
4940 }
4941
Paul Jensenc8b9a742014-09-30 15:37:41 -04004942 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004943 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4944 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004945 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004946 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004947 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4948 }
4949 }
4950
Robert Greenwalt7b816022014-04-18 15:25:25 -07004951 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4952 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004953 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004954 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4955 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004956 }
4957 }
4958
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004959 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4960 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004961 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004962 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004963 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4964 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004965 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004966 sendIntent(nri.mPendingIntent, intent);
4967 }
4968 // else not handled
4969 }
4970
4971 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4972 mPendingIntentWakeLock.acquire();
4973 try {
4974 if (DBG) log("Sending " + pendingIntent);
4975 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4976 } catch (PendingIntent.CanceledException e) {
4977 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4978 mPendingIntentWakeLock.release();
4979 releasePendingNetworkRequest(pendingIntent);
4980 }
4981 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4982 }
4983
4984 @Override
4985 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4986 String resultData, Bundle resultExtras) {
4987 if (DBG) log("Finished sending " + pendingIntent);
4988 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004989 // Release with a delay so the receiving client has an opportunity to put in its
4990 // own request.
4991 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004992 }
4993
Chalard Jeanf19db372018-01-26 19:24:40 +09004994 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004995 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004996 if (nri.messenger == null) {
4997 return; // Default request has no msgr
4998 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004999 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005000 // TODO: check if defensive copies of data is needed.
5001 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005002 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005003 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5004 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005005 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005006 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005007 case ConnectivityManager.CALLBACK_AVAILABLE: {
5008 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5009 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5010 break;
5011 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005012 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005013 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005014 break;
5015 }
5016 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005017 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09005018 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
5019 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005020 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005021 break;
5022 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005023 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005024 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005025 break;
5026 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005027 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005028 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005029 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005030 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005031 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005032 String notification = ConnectivityManager.getCallbackName(notificationType);
5033 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005034 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005035 nri.messenger.send(msg);
5036 } catch (RemoteException e) {
5037 // may occur naturally in the race of binder death.
5038 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5039 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005040 }
5041
Hugo Benichidba33db2017-03-23 22:40:44 +09005042 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5043 bundle.putParcelable(t.getClass().getSimpleName(), t);
5044 }
5045
Paul Jensenc8b9a742014-09-30 15:37:41 -04005046 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005047 if (nai.numRequestNetworkRequests() != 0) {
5048 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5049 NetworkRequest nr = nai.requestAt(i);
5050 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005051 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005052 loge("Dead network still had at least " + nr);
5053 break;
5054 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005055 }
5056 nai.asyncChannel.disconnect();
5057 }
5058
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5060 if (oldNetwork == null) {
5061 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5062 return;
5063 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005064 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005065
5066 // If we get here it means that the last linger timeout for this network expired. So there
5067 // must be no other active linger timers, and we must stop lingering.
5068 oldNetwork.clearLingerState();
5069
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005070 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005071 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005072 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005073 } else {
5074 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005075 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5076 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005077 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005078 }
5079
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005080 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005081 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005082 setupDataActivityTracking(newNetwork);
5083 try {
5084 mNetd.setDefaultNetId(newNetwork.network.netId);
5085 } catch (Exception e) {
5086 loge("Exception setting default network :" + e);
5087 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005088
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005089 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005090 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005091 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005092 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005093 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005094 }
5095
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005096 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005097 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5098 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5099 NetworkRequest nr = nri.request;
5100 if (!nr.isListen()) continue;
5101 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5102 nai.removeRequest(nri.request.requestId);
5103 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5104 }
5105 }
5106
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005107 if (capabilitiesChanged) {
5108 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5109 }
5110
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005111 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5112 NetworkRequest nr = nri.request;
5113 if (!nr.isListen()) continue;
5114 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5115 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005116 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005117 }
5118 }
5119 }
5120
Paul Jensen2161a8e2014-09-11 11:00:39 -04005121 // Handles a network appearing or improving its score.
5122 //
5123 // - Evaluates all current NetworkRequests that can be
5124 // satisfied by newNetwork, and reassigns to newNetwork
5125 // any such requests for which newNetwork is the best.
5126 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005127 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005128 // needed. A network is needed if it is the best network for
5129 // one or more NetworkRequests, or if it is a VPN.
5130 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005131 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005132 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005133 //
5134 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5135 // networks that have no chance (i.e. even if validated)
5136 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005137 //
5138 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5139 // it does not remove NetworkRequests that other Networks could better satisfy.
5140 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5141 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5142 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005143 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005144 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005145 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5146 // performed to tear down unvalidated networks that have no chance (i.e. even if
5147 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005148 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005149 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005150 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005151 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005152 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005153 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005154
5155 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5156 final int score = newNetwork.getCurrentScore();
5157
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005158 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005159
Paul Jensen2161a8e2014-09-11 11:00:39 -04005160 // Find and migrate to this Network any NetworkRequests for
5161 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005162 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005163 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005164 NetworkCapabilities nc = newNetwork.networkCapabilities;
5165 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005166 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005167 // Process requests in the first pass and listens in the second pass. This allows us to
5168 // change a network's capabilities depending on which requests it has. This is only
5169 // correct if the change in capabilities doesn't affect whether the network satisfies
5170 // requests or not, and doesn't affect the network's score.
5171 if (nri.request.isListen()) continue;
5172
Hugo Benichicd952782017-09-20 11:20:14 +09005173 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005174 final boolean satisfies = newNetwork.satisfies(nri.request);
5175 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005176 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005177 log("Network " + newNetwork.name() + " was already satisfying" +
5178 " request " + nri.request.requestId + ". No change.");
5179 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005180 keep = true;
5181 continue;
5182 }
5183
5184 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005185 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005186 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 // next check if it's better than any current network we're using for
5188 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005189 if (VDBG) {
5190 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005191 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005192 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005193 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005194 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005195 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005196 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005197 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005198 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005199 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005200 affectedNetworks.add(currentNetwork);
5201 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005202 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005203 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005204 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005205 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005206 if (!newNetwork.addRequest(nri.request)) {
5207 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5208 }
5209 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005210 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005211 // Tell NetworkFactories about the new score, so they can stop
5212 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213 // TODO - this could get expensive if we have alot of requests for this
5214 // network. Think about if there is a way to reduce this. Push
5215 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005216 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005217 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005218 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005219 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005220 if (currentNetwork != null) {
5221 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5222 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005223 }
5224 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005225 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005226 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5227 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005228 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005229 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5230 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5231 // This means this code doesn't have to handle the case where "currentNetwork" no
5232 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5233 if (DBG) {
5234 log("Network " + newNetwork.name() + " stopped satisfying" +
5235 " request " + nri.request.requestId);
5236 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005237 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005238 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005239 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005240 sendUpdatedScoreToFactories(nri.request, 0);
5241 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005242 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5243 newNetwork.name() +
5244 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005245 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005246 // TODO: Technically, sending CALLBACK_LOST here is
5247 // incorrect if there is a replacement network currently
5248 // connected that can satisfy nri, which is a request
5249 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005250 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5251 // so this code is only incorrect for a network that loses
5252 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005253 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005254 }
5255 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005256 if (isNewDefault) {
5257 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005258 makeDefault(newNetwork);
5259 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005260 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005261 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005262 // Have a new default network, release the transition wakelock in
5263 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005264 }
5265
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005266 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5267 Slog.wtf(TAG, String.format(
5268 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005269 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005270 }
5271 if (newNetwork.getCurrentScore() != score) {
5272 Slog.wtf(TAG, String.format(
5273 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005274 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005275 }
5276
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005277 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005278 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5279 // If the network went from background to foreground or vice versa, we need to update
5280 // its foreground state. It is safe to do this after rematching the requests because
5281 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5282 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005283 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005284 } else {
5285 processListenRequests(newNetwork, false);
5286 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005287
Paul Jensencf4c2c62015-07-01 14:16:32 -04005288 // do this after the default net is switched, but
5289 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005290 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005291
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005292 // Linger any networks that are no longer needed. This should be done after sending the
5293 // available callback for newNetwork.
5294 for (NetworkAgentInfo nai : affectedNetworks) {
5295 updateLingerState(nai, now);
5296 }
5297 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5298 // does not need to be done in any particular order.
5299 updateLingerState(newNetwork, now);
5300
Paul Jensencf4c2c62015-07-01 14:16:32 -04005301 if (isNewDefault) {
5302 // Maintain the illusion: since the legacy API only
5303 // understands one network at a time, we must pretend
5304 // that the current default network disconnected before
5305 // the new one connected.
5306 if (oldDefaultNetwork != null) {
5307 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5308 oldDefaultNetwork, true);
5309 }
5310 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5311 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5312 notifyLockdownVpn(newNetwork);
5313 }
5314
Robert Greenwalt7b816022014-04-18 15:25:25 -07005315 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005316 // Notify battery stats service about this network, both the normal
5317 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005318 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005319 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005320 final IBatteryStats bs = BatteryStatsService.getService();
5321 final int type = newNetwork.networkInfo.getType();
5322
5323 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5324 bs.noteNetworkInterfaceType(baseIface, type);
5325 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5326 final String stackedIface = stacked.getInterfaceName();
5327 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005328 }
5329 } catch (RemoteException ignored) {
5330 }
5331
Robert Greenwalt152ed372014-12-17 17:19:53 -08005332 // This has to happen after the notifyNetworkCallbacks as that tickles each
5333 // ConnectivityManager instance so that legacy requests correctly bind dns
5334 // requests to this network. The legacy users are listening for this bcast
5335 // and will generally do a dns request so they can ensureRouteToHost and if
5336 // they do that before the callbacks happen they'll use the default network.
5337 //
5338 // TODO: Is there still a race here? We send the broadcast
5339 // after sending the callback, but if the app can receive the
5340 // broadcast before the callback, it might still break.
5341 //
5342 // This *does* introduce a race where if the user uses the new api
5343 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5344 // they may get old info. Reverse this after the old startUsing api is removed.
5345 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005346 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5347 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005348 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005349 // legacy type tracker filters out repeat adds
5350 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5351 }
5352 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005353
5354 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5355 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5356 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5357 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5358 if (newNetwork.isVPN()) {
5359 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5360 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005361 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005362 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5363 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005364 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005365 if (nai.getLingerExpiry() > 0) {
5366 // This network has active linger timers and no requests, but is not
5367 // lingering. Linger it.
5368 //
5369 // One way (the only way?) this can happen if this network is unvalidated
5370 // and became unneeded due to another network improving its score to the
5371 // point where this network will no longer be able to satisfy any requests
5372 // even if it validates.
5373 updateLingerState(nai, now);
5374 } else {
5375 if (DBG) log("Reaping " + nai.name());
5376 teardownUnneededNetwork(nai);
5377 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005378 }
5379 }
5380 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005381 }
5382
Paul Jensen1c7ba022015-06-16 14:27:36 -04005383 /**
5384 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5385 * being disconnected.
5386 * @param changed If only one Network's score or capabilities have been modified since the last
5387 * time this function was called, pass this Network in this argument, otherwise pass
5388 * null.
5389 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5390 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5391 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5392 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5393 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005394 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005395 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005396 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5397 // to avoid the slowness. It is not simply enough to process just "changed", for
5398 // example in the case where "changed"'s score decreases and another network should begin
5399 // satifying a NetworkRequest that "changed" currently satisfies.
5400
5401 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5402 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5403 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005404 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005405 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005406 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005407 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005408 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5409 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5410 // Rematch higher scoring networks first to prevent requests first matching a lower
5411 // scoring network and then a higher scoring network, which could produce multiple
5412 // callbacks and inadvertently unlinger networks.
5413 Arrays.sort(nais);
5414 for (NetworkAgentInfo nai : nais) {
5415 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005416 // Only reap the last time through the loop. Reaping before all rematching
5417 // is complete could incorrectly teardown a network that hasn't yet been
5418 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005419 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005420 : ReapUnvalidatedNetworks.REAP,
5421 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005422 }
5423 }
5424 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005425
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005426 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005427 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005428 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005429 // For now only update icons for default connection.
5430 // TODO: Update WiFi and cellular icons separately. b/17237507
5431 if (!isDefaultNetwork(nai)) return;
5432
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005433 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005434 // Don't repeat publish.
5435 if (newInetCondition == mDefaultInetConditionPublished) return;
5436
5437 mDefaultInetConditionPublished = newInetCondition;
5438 sendInetConditionBroadcast(nai.networkInfo);
5439 }
5440
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005441 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005442 synchronized (mVpns) {
5443 if (mLockdownTracker != null) {
5444 if (nai != null && nai.isVPN()) {
5445 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5446 } else {
5447 mLockdownTracker.onNetworkInfoChanged();
5448 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005449 }
5450 }
5451 }
5452
Robert Greenwalt7b816022014-04-18 15:25:25 -07005453 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005454 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005455 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005456 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005457 synchronized (networkAgent) {
5458 oldInfo = networkAgent.networkInfo;
5459 networkAgent.networkInfo = newInfo;
5460 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005461 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005462
Robert Greenwalt7b816022014-04-18 15:25:25 -07005463 if (DBG) {
5464 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5465 (oldInfo == null ? "null" : oldInfo.getState()) +
5466 " to " + state);
5467 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005468
Robin Lee585e2482016-05-01 23:00:00 +01005469 if (!networkAgent.created
5470 && (state == NetworkInfo.State.CONNECTED
5471 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005472
5473 // A network that has just connected has zero requests and is thus a foreground network.
5474 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5475
Robert Greenwalt7b816022014-04-18 15:25:25 -07005476 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005477 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005478 if (networkAgent.isVPN()) {
5479 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005480 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5481 (networkAgent.networkMisc == null ||
5482 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005483 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005484 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005485 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005486 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005487 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005488 loge("Error creating network " + networkAgent.network.netId + ": "
5489 + e.getMessage());
5490 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005491 }
Paul Jenseneec75412014-08-04 12:21:19 -04005492 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005493 }
5494
5495 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5496 networkAgent.everConnected = true;
5497
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005498 if (networkAgent.linkProperties == null) {
5499 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5500 }
5501
Robert Greenwalt7b816022014-04-18 15:25:25 -07005502 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005503
Paul Jensenca8f16a2014-05-09 12:47:55 -04005504 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005505 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005506
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005507 if (networkAgent.isVPN()) {
5508 // Temporarily disable the default proxy (not global).
5509 synchronized (mProxyLock) {
5510 if (!mDefaultProxyDisabled) {
5511 mDefaultProxyDisabled = true;
5512 if (mGlobalProxy == null && mDefaultProxy != null) {
5513 sendProxyBroadcast(null);
5514 }
5515 }
5516 }
5517 // TODO: support proxy per network.
5518 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005519
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005520 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5521 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5522 // capabilities, so it only needs to be done once on initial connect, not every time the
5523 // network's capabilities change. Note that we do this before rematching the network,
5524 // so we could decide to tear it down immediately afterwards. That's fine though - on
5525 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5526 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005527 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005528
Paul Jensen2161a8e2014-09-11 11:00:39 -04005529 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005530 final long now = SystemClock.elapsedRealtime();
5531 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005532
5533 // This has to happen after matching the requests, because callbacks are just requests.
5534 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005535 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005536 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005537 if (networkAgent.isVPN()) {
5538 synchronized (mProxyLock) {
5539 if (mDefaultProxyDisabled) {
5540 mDefaultProxyDisabled = false;
5541 if (mGlobalProxy == null && mDefaultProxy != null) {
5542 sendProxyBroadcast(mDefaultProxy);
5543 }
5544 }
5545 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005546 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005547 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005548 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5549 state == NetworkInfo.State.SUSPENDED) {
5550 // going into or coming out of SUSPEND: rescore and notify
5551 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005552 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005553 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005554 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5555 networkAgent.networkCapabilities);
5556 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5557 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005558 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5559 ConnectivityManager.CALLBACK_SUSPENDED :
5560 ConnectivityManager.CALLBACK_RESUMED));
5561 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005562 }
5563 }
5564
Robert Greenwaltac96c522014-06-03 16:43:57 -07005565 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005566 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005567 if (score < 0) {
5568 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5569 "). Bumping score to min of 0");
5570 score = 0;
5571 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005572
Paul Jensen2161a8e2014-09-11 11:00:39 -04005573 final int oldScore = nai.getCurrentScore();
5574 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005575
Paul Jensen85cf78e2015-06-25 13:25:07 -04005576 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005577
Paul Jensenc8b9a742014-09-30 15:37:41 -04005578 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005579 }
5580
Erik Klinec75d4fa2017-02-15 19:59:17 +09005581 // Notify only this one new request of the current state. Transfer all the
5582 // current state by calling NetworkCapabilities and LinkProperties callbacks
5583 // so that callers can be guaranteed to have as close to atomicity in state
5584 // transfer as can be supported by this current API.
5585 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005586 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005587 if (nri.mPendingIntent != null) {
5588 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5589 // Attempt no subsequent state pushes where intents are involved.
5590 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005591 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005592
5593 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005594 }
5595
Robert Greenwalt8d482522015-06-24 13:23:42 -07005596 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005597 // The NetworkInfo we actually send out has no bearing on the real
5598 // state of affairs. For example, if the default connection is mobile,
5599 // and a request for HIPRI has just gone away, we need to pretend that
5600 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5601 // the state to DISCONNECTED, even though the network is of type MOBILE
5602 // and is still connected.
5603 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5604 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005605 if (state != DetailedState.DISCONNECTED) {
5606 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005607 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005608 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005609 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005610 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5611 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5612 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5613 if (info.isFailover()) {
5614 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5615 nai.networkInfo.setFailover(false);
5616 }
5617 if (info.getReason() != null) {
5618 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5619 }
5620 if (info.getExtraInfo() != null) {
5621 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5622 }
5623 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005624 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005625 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005626 if (newDefaultAgent != null) {
5627 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5628 newDefaultAgent.networkInfo);
5629 } else {
5630 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5631 }
5632 }
5633 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5634 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005635 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005636 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005637 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005638 }
5639 }
5640 }
5641
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005642 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005643 if (VDBG) {
5644 String notification = ConnectivityManager.getCallbackName(notifyType);
5645 log("notifyType " + notification + " for " + networkAgent.name());
5646 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005647 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5648 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005649 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5650 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005651 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5652 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005653 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005654 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005655 } else {
5656 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5657 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005658 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005659 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005660
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005661 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5662 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5663 }
5664
Jeff Sharkey69736342014-12-08 14:50:12 -08005665 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005666 * Returns the list of all interfaces that could be used by network traffic that does not
5667 * explicitly specify a network. This includes the default network, but also all VPNs that are
5668 * currently connected.
5669 *
5670 * Must be called on the handler thread.
5671 */
5672 private Network[] getDefaultNetworks() {
5673 ArrayList<Network> defaultNetworks = new ArrayList<>();
5674 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5675 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5676 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5677 defaultNetworks.add(nai.network);
5678 }
5679 }
5680 return defaultNetworks.toArray(new Network[0]);
5681 }
5682
5683 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005684 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5685 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005686 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005687 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005688 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005689 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005690 } catch (Exception ignored) {
5691 }
5692 }
5693
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005694 @Override
5695 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005696 int user = UserHandle.getUserId(Binder.getCallingUid());
5697 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005698 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005699 return mVpns.get(user).addAddress(address, prefixLength);
5700 }
5701 }
5702
5703 @Override
5704 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005705 int user = UserHandle.getUserId(Binder.getCallingUid());
5706 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005707 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005708 return mVpns.get(user).removeAddress(address, prefixLength);
5709 }
5710 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005711
5712 @Override
5713 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005714 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005715 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005716 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005717 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005718 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005719 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005720 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005721 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005722 }
5723 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005724 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005725
5726 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005727 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005728 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005729 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005730 }
5731
5732 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005733 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5734 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5735 enforceKeepalivePermission();
5736 mKeepaliveTracker.startNattKeepalive(
5737 getNetworkAgentInfoForNetwork(network),
5738 intervalSeconds, messenger, binder,
5739 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5740 }
5741
5742 @Override
5743 public void stopKeepalive(Network network, int slot) {
5744 mHandler.sendMessage(mHandler.obtainMessage(
5745 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5746 }
5747
5748 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005749 public void factoryReset() {
5750 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005751
5752 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5753 return;
5754 }
5755
Robin Lee3b3dd942015-05-12 18:14:58 +01005756 final int userId = UserHandle.getCallingUserId();
5757
Stuart Scottf1fb3972015-04-02 18:00:02 -07005758 // Turn airplane mode off
5759 setAirplaneMode(false);
5760
Stuart Scotte3e314d2015-04-20 14:07:45 -07005761 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5762 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005763 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005764 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005765 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005766 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005767 }
5768
Stuart Scotte3e314d2015-04-20 14:07:45 -07005769 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005770 // Remove always-on package
5771 synchronized (mVpns) {
5772 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5773 if (alwaysOnPackage != null) {
5774 setAlwaysOnVpnPackage(userId, null, false);
5775 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5776 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005777
Hugo Benichi69744342017-11-27 10:57:16 +09005778 // Turn Always-on VPN off
5779 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5780 final long ident = Binder.clearCallingIdentity();
5781 try {
5782 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5783 mLockdownEnabled = false;
5784 setLockdownTracker(null);
5785 } finally {
5786 Binder.restoreCallingIdentity(ident);
5787 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005788 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005789
Hugo Benichi69744342017-11-27 10:57:16 +09005790 // Turn VPN off
5791 VpnConfig vpnConfig = getVpnConfig(userId);
5792 if (vpnConfig != null) {
5793 if (vpnConfig.legacy) {
5794 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5795 } else {
5796 // Prevent this app (packagename = vpnConfig.user) from initiating
5797 // VPN connections in the future without user intervention.
5798 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005799
Hugo Benichi69744342017-11-27 10:57:16 +09005800 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5801 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005802 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005803 }
5804 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005805
5806 Settings.Global.putString(mContext.getContentResolver(),
5807 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005808 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005809
Ricky Wai44dcbde2018-01-23 04:09:45 +00005810 @Override
5811 public byte[] getNetworkWatchlistConfigHash() {
5812 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5813 if (nwm == null) {
5814 loge("Unable to get NetworkWatchlistManager");
5815 return null;
5816 }
5817 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5818 return nwm.getWatchlistConfigHash();
5819 }
5820
Paul Jensencf4c2c62015-07-01 14:16:32 -04005821 @VisibleForTesting
5822 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5823 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5824 return new NetworkMonitor(context, handler, nai, defaultRequest);
5825 }
Erik Kline48f12f22016-04-14 17:30:59 +09005826
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005827 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005828 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5829 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005830 }
5831
5832 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005833 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5834 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5835 }
5836
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005837 @VisibleForTesting
5838 public boolean hasService(String name) {
5839 return ServiceManager.checkService(name) != null;
5840 }
5841
Hugo Benichi64901e52017-10-19 14:42:40 +09005842 @VisibleForTesting
5843 protected IpConnectivityMetrics.Logger metricsLogger() {
5844 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5845 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005846 }
5847
5848 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005849 int[] transports = nai.networkCapabilities.getTransportTypes();
5850 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005851 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005852
5853 private static boolean toBool(int encodedBoolean) {
5854 return encodedBoolean != 0; // Only 0 means false.
5855 }
5856
5857 private static int encodeBool(boolean b) {
5858 return b ? 1 : 0;
5859 }
mswest46386886f2018-03-12 10:34:34 -07005860
5861 @Override
5862 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5863 FileDescriptor err, String[] args, ShellCallback callback,
5864 ResultReceiver resultReceiver) {
5865 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5866 }
5867
5868 private class ShellCmd extends ShellCommand {
5869
5870 @Override
5871 public int onCommand(String cmd) {
5872 if (cmd == null) {
5873 return handleDefaultCommands(cmd);
5874 }
5875 final PrintWriter pw = getOutPrintWriter();
5876 try {
5877 switch (cmd) {
5878 case "airplane-mode":
5879 final String action = getNextArg();
5880 if ("enable".equals(action)) {
5881 setAirplaneMode(true);
5882 return 0;
5883 } else if ("disable".equals(action)) {
5884 setAirplaneMode(false);
5885 return 0;
5886 } else if (action == null) {
5887 final ContentResolver cr = mContext.getContentResolver();
5888 final int enabled = Settings.Global.getInt(cr,
5889 Settings.Global.AIRPLANE_MODE_ON);
5890 pw.println(enabled == 0 ? "disabled" : "enabled");
5891 return 0;
5892 } else {
5893 onHelp();
5894 return -1;
5895 }
5896 default:
5897 return handleDefaultCommands(cmd);
5898 }
5899 } catch (Exception e) {
5900 pw.println(e);
5901 }
5902 return -1;
5903 }
5904
5905 @Override
5906 public void onHelp() {
5907 PrintWriter pw = getOutPrintWriter();
5908 pw.println("Connectivity service commands:");
5909 pw.println(" help");
5910 pw.println(" Print this help text.");
5911 pw.println(" airplane-mode [enable|disable]");
5912 pw.println(" Turn airplane mode on or off.");
5913 pw.println(" airplane-mode");
5914 pw.println(" Get airplane mode.");
5915 }
5916 }
5917}