blob: 088f366b5f19f545c2b2b48abcc2371da6ae6af4 [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;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900104import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700105import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400106import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700108import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700109import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700110import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700111import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900112import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700113import android.util.LocalLog;
114import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600115import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800116import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700117import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500118import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
Wink Savilleab9321d2013-06-29 21:10:57 -0700122import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400123import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400124import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700125import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700126import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700127import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700128import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800129import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700130import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700131import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600132import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700133import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900134import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900135import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700136import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700137import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400138import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900139import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900140import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900141import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900142import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100143import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700144import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900145import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700146import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400148import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900149import com.android.server.connectivity.NetworkNotificationManager;
150import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400151import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700152import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800153import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700154import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100155import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700156import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700157import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900158import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700159import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600160
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700161import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700162
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700163import org.xmlpull.v1.XmlPullParser;
164import org.xmlpull.v1.XmlPullParserException;
165
166import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700168import java.io.FileNotFoundException;
169import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700170import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700172import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700173import java.net.InetAddress;
174import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700175import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700177import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700178import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700179import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700180import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700181import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700182import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700183import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900184import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600185import java.util.SortedSet;
186import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188/**
189 * @hide
190 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800191public class ConnectivityService extends IConnectivityManager.Stub
192 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900193 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Erik Kline7747fd42017-05-12 16:52:48 +0900195 public static final String DIAG_ARG = "--diag";
196 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900197 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900198
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900199 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700200 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Jake Hamby786e71a2014-02-06 14:43:50 -0800202 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900203 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204
Jeff Sharkey899223b2012-08-04 15:24:58 -0700205 // TODO: create better separation between radio types and network types
206
Robert Greenwalt42acef32009-08-12 16:08:25 -0700207 // how long to wait before switching back to a radio's default network
208 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
209 // system property that can override the above value
210 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
211 "android.telephony.apn-restore";
212
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900213 // How long to wait before putting up a "This network doesn't have an Internet connection,
214 // connect anyway?" dialog after the user selects a network that doesn't validate.
215 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
216
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900217 // Default to 30s linger time-out. Modifiable only for testing.
218 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
219 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
220 @VisibleForTesting
221 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
222
Jeremy Joslin79294842014-12-03 17:15:28 -0800223 // How long to delay to removal of a pending intent based request.
224 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
225 private final int mReleasePendingIntentDelayMs;
226
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900227 private MockableSystemProperties mSystemProperties;
228
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800229 private Tethering mTethering;
230
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700231 private final PermissionMonitor mPermissionMonitor;
232
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700233 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700234
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700235 @GuardedBy("mVpns")
236 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700237
Hugo Benichi69744342017-11-27 10:57:16 +0900238 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
239 // a direct call to LockdownVpnTracker.isEnabled().
240 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700241 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900242 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700243 private LockdownVpnTracker mLockdownTracker;
244
Erik Klineda4bfa82015-04-30 12:58:40 +0900245 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700247 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700248 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700251 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700253 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800254 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700255 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900256 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700257
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700258 private String mCurrentTcpBufferSizes;
259
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700260 private static final int ENABLED = 1;
261 private static final int DISABLED = 0;
262
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900263 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900264 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
265 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900266
Paul Jensenb10e37f2014-11-25 12:33:08 -0500267 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400268 // Tear down networks that have no chance (e.g. even if validated) of becoming
269 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500270 // all networks have been rematched against all NetworkRequests.
271 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400272 // Don't reap networks. This should be passed when some networks have not yet been
273 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500274 DONT_REAP
275 };
276
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900277 private enum UnneededFor {
278 LINGER, // Determine whether this network is unneeded and should be lingered.
279 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
280 }
281
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700283 * used internally to change our mobile data enabled flag
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700286
287 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700289 * from one net to another. Clear happens when we get a new
290 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
291 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700294
Robert Greenwalt434203a2010-10-11 16:00:27 -0700295 /**
296 * used internally to reload global proxy settings
297 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700298 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700299
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700300 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400301 * PAC manager has received new port.
302 */
303 private static final int EVENT_PROXY_HAS_CHANGED = 16;
304
Robert Greenwalte049c232014-04-11 15:53:27 -0700305 /**
306 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700307 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700308 */
309 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
310
Robert Greenwalt7b816022014-04-18 15:25:25 -0700311 /**
312 * used internally when registering NetworkAgents
313 * obj = Messenger
314 */
315 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
316
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 /**
318 * used to add a network request
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
322
323 /**
324 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900325 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700326 * cancel it.
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
330
331 /**
332 * used to add a network listener - no request
333 * includes a NetworkRequestInfo
334 */
335 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
336
337 /**
338 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400339 * arg1 = UID of caller
340 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700341 */
342 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
343
Robert Greenwalta67be032014-05-16 15:49:14 -0700344 /**
345 * used internally when registering NetworkFactories
346 * obj = Messenger
347 */
348 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
349
Robert Greenwalt27711812014-06-25 16:45:57 -0700350 /**
351 * used internally to expire a wakelock when transitioning
352 * from one net to another. Expire happens when we fail to find
353 * a new network (typically after 1 minute) -
354 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
355 * a replacement network.
356 */
357 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
358
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700359 /**
360 * Used internally to indicate the system is ready.
361 */
362 private static final int EVENT_SYSTEM_READY = 25;
363
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800364 /**
365 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400366 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800367 */
368 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
369
370 /**
371 * used to remove a pending intent and its associated network request.
372 * arg1 = UID of caller
373 * obj = PendingIntent
374 */
375 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
376
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900377 /**
378 * used to specify whether a network should be used even if unvalidated.
379 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
380 * arg2 = whether to remember this choice in the future (1 or 0)
381 * obj = network
382 */
383 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
384
385 /**
386 * used to ask the user to confirm a connection to an unvalidated network.
387 * obj = network
388 */
389 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700390
Erik Klineda4bfa82015-04-30 12:58:40 +0900391 /**
392 * used internally to (re)configure mobile data always-on settings.
393 */
394 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
395
Paul Jensen694f2b82015-06-17 14:15:39 -0400396 /**
397 * used to add a network listener with a pending intent
398 * obj = NetworkRequestInfo
399 */
400 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
401
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900402 /**
403 * used to specify whether a network should not be penalized when it becomes unvalidated.
404 */
405 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
406
407 /**
408 * used to trigger revalidation of a network.
409 */
410 private static final int EVENT_REVALIDATE_NETWORK = 36;
411
Erik Klinea24d4592018-01-11 21:07:29 +0900412 // Handle changes in Private DNS settings.
413 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
414
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900415 private static String eventName(int what) {
416 return sMagicDecoderRing.get(what, Integer.toString(what));
417 }
418
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900419 /** Handler thread used for both of the handlers below. */
420 @VisibleForTesting
421 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700422 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700423 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700424 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700425 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900426 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700427
Mike Lockwood0f79b542009-08-14 14:18:49 -0400428 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800429 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400430
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700431 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700432 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800433 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700434
Robert Greenwalt434203a2010-10-11 16:00:27 -0700435 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400436 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700437 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700438 private boolean mDefaultProxyDisabled = false;
439
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400441 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700442
Jason Monk602b2322013-07-03 17:04:33 -0400443 private PacManager mPacManager = null;
444
Erik Klineda4bfa82015-04-30 12:58:40 +0900445 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700446
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400447 private UserManager mUserManager;
448
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700449 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700450 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700451
Robert Greenwalt50393202011-06-21 17:26:14 -0700452 // the set of network types that can only be enabled by system/sig apps
453 List mProtectedNetworks;
454
John Spurlockbf991a82013-06-24 14:20:23 -0400455 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700456
Wink Savilleab9321d2013-06-29 21:10:57 -0700457 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400458
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900459 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900460 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900461 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900462
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700463 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800464 private static final int MIN_NET_ID = 100; // some reserved marks
465 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700466 private int mNextNetId = MIN_NET_ID;
467
Robert Greenwalt34524f02014-05-18 16:22:10 -0700468 // sequence number of NetworkRequests
469 private int mNextNetworkRequestId = 1;
470
Erik Kline7523eb32015-07-09 18:24:03 +0900471 // NetworkRequest activity String log entries.
472 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
473 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
474
Hugo Benichic2ae2872016-07-11 11:05:12 +0900475 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900476 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900477 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
478
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900479 private static final int MAX_WAKELOCK_LOGS = 20;
480 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900481 private int mTotalWakelockAcquisitions = 0;
482 private int mTotalWakelockReleases = 0;
483 private long mTotalWakelockDurationMs = 0;
484 private long mMaxWakelockDurationMs = 0;
485 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900486
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
488 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400489 private static class ValidationLog {
490 final Network mNetwork;
491 final String mNetworkExtraInfo;
492 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700493
Paul Jensen0808eb82016-06-03 13:51:21 -0400494 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
495 mNetwork = network;
496 mNetworkExtraInfo = networkExtraInfo;
497 mLog = log;
498 }
499 }
500 private final ArrayDeque<ValidationLog> mValidationLogs =
501 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
502
503 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900504 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700505 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
506 mValidationLogs.removeLast();
507 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400508 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700509 }
510 }
511
Hugo Benichif9fdf872016-07-28 17:53:06 +0900512 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900513
Erik Kline065ab6e2016-10-02 18:02:14 +0900514 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900515 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900516
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900517 @VisibleForTesting
518 final MultipathPolicyTracker mMultipathPolicyTracker;
519
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 /**
521 * Implements support for the legacy "one network per network type" model.
522 *
523 * We used to have a static array of NetworkStateTrackers, one for each
524 * network type, but that doesn't work any more now that we can have,
525 * for example, more that one wifi network. This class stores all the
526 * NetworkAgentInfo objects that support a given type, but the legacy
527 * API will only see the first one.
528 *
529 * It serves two main purposes:
530 *
531 * 1. Provide information about "the network for a given type" (since this
532 * API only supports one).
533 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
534 * the first network for a given type changes, or if the default network
535 * changes.
536 */
537 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900539 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900541
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700542 /**
543 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
544 * Each list holds references to all NetworkAgentInfos that are used to
545 * satisfy requests for that network type.
546 *
547 * This array is built out at startup such that an unsupported network
548 * doesn't get an ArrayList instance, making this a tristate:
549 * unsupported, supported but not active and active.
550 *
551 * The actual lists are populated when we scan the network types that
552 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900553 *
554 * Threading model:
555 * - addSupportedType() is only called in the constructor
556 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
557 * They are therefore not thread-safe with respect to each other.
558 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
559 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
560 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563
564 public LegacyTypeTracker() {
565 mTypeLists = (ArrayList<NetworkAgentInfo>[])
566 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
567 }
568
569 public void addSupportedType(int type) {
570 if (mTypeLists[type] != null) {
571 throw new IllegalStateException(
572 "legacy list for type " + type + "already initialized");
573 }
574 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
575 }
576
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 public boolean isTypeSupported(int type) {
578 return isNetworkTypeValid(type) && mTypeLists[type] != null;
579 }
580
581 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900582 synchronized (mTypeLists) {
583 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
584 return mTypeLists[type].get(0);
585 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900587 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 }
589
Robert Greenwalt8d482522015-06-24 13:23:42 -0700590 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900591 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700593 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900595 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 }
597 }
598
599 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 public void add(int type, NetworkAgentInfo nai) {
601 if (!isTypeSupported(type)) {
602 return; // Invalid network type.
603 }
604 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
605
606 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
607 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 return;
609 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900610 synchronized (mTypeLists) {
611 list.add(nai);
612 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900613
614 // 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 +0900615 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900616 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700617 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
618 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700620 }
621
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900623 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
625 if (list == null || list.isEmpty()) {
626 return;
627 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900629
Hugo Benichi78caa2582016-06-21 09:48:07 +0900630 synchronized (mTypeLists) {
631 if (!list.remove(nai)) {
632 return;
633 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 }
635
Robert Greenwalt8d482522015-06-24 13:23:42 -0700636 final DetailedState state = DetailedState.DISCONNECTED;
637
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900638 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700639 maybeLogBroadcast(nai, state, type, wasDefault);
640 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641 }
642
643 if (!list.isEmpty() && wasFirstNetwork) {
644 if (DBG) log("Other network available for type " + type +
645 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900646 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
648 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900649 }
650 }
651
652 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900653 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
654 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900656 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 }
658 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700659
Robert Greenwalt8d482522015-06-24 13:23:42 -0700660 // send out another legacy broadcast - currently only used for suspend/unsuspend
661 // toggle
662 public void update(NetworkAgentInfo nai) {
663 final boolean isDefault = isDefaultNetwork(nai);
664 final DetailedState state = nai.networkInfo.getDetailedState();
665 for (int type = 0; type < mTypeLists.length; type++) {
666 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700667 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900668 final boolean isFirst = contains && (nai == list.get(0));
669 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 maybeLogBroadcast(nai, state, type, isDefault);
671 sendLegacyNetworkBroadcast(nai, state, type);
672 }
673 }
674 }
675
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 private String naiToString(NetworkAgentInfo nai) {
677 String name = (nai != null) ? nai.name() : "null";
678 String state = (nai.networkInfo != null) ?
679 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
680 "???/???";
681 return name + " " + state;
682 }
683
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700684 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900685 pw.println("mLegacyTypeTracker:");
686 pw.increaseIndent();
687 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900689 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700690 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900691 pw.println();
692 pw.println("Current state:");
693 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900694 synchronized (mTypeLists) {
695 for (int type = 0; type < mTypeLists.length; type++) {
696 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
697 for (NetworkAgentInfo nai : mTypeLists[type]) {
698 pw.println(type + " " + naiToString(nai));
699 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900700 }
701 }
702 pw.decreaseIndent();
703 pw.decreaseIndent();
704 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700705 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700706 }
707 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
708
Vishnu Nair5c010902017-10-26 10:08:50 -0700709 /**
710 * Helper class which parses out priority arguments and dumps sections according to their
711 * priority. If priority arguments are omitted, function calls the legacy dump command.
712 */
713 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
714 @Override
715 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
716 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
717 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
718 }
719
720 @Override
721 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
722 doDump(fd, pw, args, asProto);
723 }
724
725 @Override
726 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
727 doDump(fd, pw, args, asProto);
728 }
729 };
730
Jeff Sharkey899223b2012-08-04 15:24:58 -0700731 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700732 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900733 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
734 }
735
736 @VisibleForTesting
737 protected ConnectivityService(Context context, INetworkManagementService netManager,
738 INetworkStatsService statsService, INetworkPolicyManager policyManager,
739 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800740 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800741
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900742 mSystemProperties = getSystemProperties();
743
Hugo Benichif9fdf872016-07-28 17:53:06 +0900744 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900745 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900746 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900747 mNetworkRequests.put(mDefaultRequest, defaultNRI);
748 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900749
Chalard Jeandda156a2018-01-10 21:19:32 +0900750 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900751 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700752
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900753 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900754 mHandlerThread.start();
755 mHandler = new InternalHandler(mHandlerThread.getLooper());
756 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700757
Jeremy Joslin79294842014-12-03 17:15:28 -0800758 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
759 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
760
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900761 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900762
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700763 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700764 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800765 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700766 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900767 mPolicyManagerInternal = checkNotNull(
768 LocalServices.getService(NetworkPolicyManagerInternal.class),
769 "missing NetworkPolicyManagerInternal");
770
Jeff Sharkey82f85212012-08-24 11:17:25 -0700771 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700772 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700773
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900775 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 } catch (RemoteException e) {
777 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700778 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700779 }
780
781 final PowerManager powerManager = (PowerManager) context.getSystemService(
782 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700783 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
784 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
785 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800786 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700787
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700788 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700789
Wink Saville51f456f2013-04-23 14:26:51 -0700790 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900791 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700792 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700793 String[] naStrings = context.getResources().getStringArray(
794 com.android.internal.R.array.networkAttributes);
795 for (String naString : naStrings) {
796 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700797 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700798 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700799 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800800 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700801 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700802 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700803 }
Wink Saville51f456f2013-04-23 14:26:51 -0700804 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
805 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
806 n.type);
807 continue;
808 }
Wink Saville975c8482011-04-07 14:23:45 -0700809 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800810 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700811 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700812 continue;
813 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700814 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700815
Wink Saville975c8482011-04-07 14:23:45 -0700816 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700817 mNetworksDefined++;
818 } catch(Exception e) {
819 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700820 }
821 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700822
823 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
824 if (mNetConfigs[TYPE_VPN] == null) {
825 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
826 // don't need to add TYPE_VPN to mNetConfigs.
827 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
828 mNetworksDefined++; // used only in the log() statement below.
829 }
830
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900831 // Do the same for Ethernet, since it's often not specified in the configs, although many
832 // devices can use it via USB host adapters.
833 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
834 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
835 mNetworksDefined++;
836 }
837
Wink Saville5e56bc52013-07-29 15:00:57 -0700838 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700839
Robert Greenwalt50393202011-06-21 17:26:14 -0700840 mProtectedNetworks = new ArrayList<Integer>();
841 int[] protectedNetworks = context.getResources().getIntArray(
842 com.android.internal.R.array.config_protectedNetworks);
843 for (int p : protectedNetworks) {
844 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
845 mProtectedNetworks.add(p);
846 } else {
847 if (DBG) loge("Ignoring protectedNetwork " + p);
848 }
849 }
850
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900851 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
852 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700853
Erik Kline47222fc2017-04-30 19:36:15 +0900854 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800855
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700856 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
857
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700858 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700859 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100860 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700861 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700862 intentFilter.addAction(Intent.ACTION_USER_ADDED);
863 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000864 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700865 mContext.registerReceiverAsUser(
866 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000867 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
868 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900869
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700870 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700871 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700872 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700873 } catch (RemoteException e) {
874 loge("Error registering observer :" + e);
875 }
876
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 mSettingsObserver = new SettingsObserver(mContext, mHandler);
878 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800879
John Spurlockbf991a82013-06-24 14:20:23 -0400880 mDataConnectionStats = new DataConnectionStats(mContext);
881 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400882
Jason Monkdecd2952013-10-10 14:02:51 -0400883 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700884
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400885 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900886
887 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900888 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
889 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900890
891 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
892 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
893 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
894 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
895 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
896 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
897 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900898
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900899 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900900 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900901 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900902
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900903 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
904
Erik Kline1742fe12017-12-13 19:40:49 +0900905 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900906 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700908
Erik Kline47222fc2017-04-30 19:36:15 +0900909 private Tethering makeTethering() {
910 // TODO: Move other elements into @Overridden getters.
911 final TetheringDependencies deps = new TetheringDependencies();
912 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
913 IoThread.get().getLooper(), new MockableSystemProperties(),
914 deps);
915 }
916
Chalard Jeandda156a2018-01-10 21:19:32 +0900917 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900918 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900919 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900920 netCap.addCapability(NET_CAPABILITY_INTERNET);
921 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900922 if (transportType > -1) {
923 netCap.addTransportType(transportType);
924 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900925 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900926 }
927
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900928 // Used only for testing.
929 // TODO: Delete this and either:
930 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
931 // changing ContentResolver to make registerContentObserver non-final).
932 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
933 // by subclassing SettingsObserver.
934 @VisibleForTesting
935 void updateMobileDataAlwaysOn() {
936 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
937 }
938
Erik Klineda4bfa82015-04-30 12:58:40 +0900939 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900940 final boolean enable = toBool(Settings.Global.getInt(
941 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900942 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
943 if (enable == isEnabled) {
944 return; // Nothing to do.
945 }
946
947 if (enable) {
948 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900949 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900950 } else {
951 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
952 }
953 }
954
955 private void registerSettingsCallbacks() {
956 // Watch for global HTTP proxy changes.
957 mSettingsObserver.observe(
958 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
959 EVENT_APPLY_GLOBAL_HTTP_PROXY);
960
961 // Watch for whether or not to keep mobile data always on.
962 mSettingsObserver.observe(
963 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
964 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
965 }
966
Erik Klinea24d4592018-01-11 21:07:29 +0900967 private void registerPrivateDnsSettingsCallbacks() {
968 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
969 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
970 }
971 }
972
Robert Greenwalt34524f02014-05-18 16:22:10 -0700973 private synchronized int nextNetworkRequestId() {
974 return mNextNetworkRequestId++;
975 }
976
Paul Jensen67b0b072015-06-10 11:22:17 -0400977 @VisibleForTesting
978 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400979 synchronized (mNetworkForNetId) {
980 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
981 int netId = mNextNetId;
982 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
983 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500984 if (!mNetIdInUse.get(netId)) {
985 mNetIdInUse.put(netId, true);
986 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400987 }
988 }
989 }
990 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700991 }
992
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600993 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600995 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
996 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600998 state = nai.getNetworkState();
999 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001000 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001001 final NetworkInfo info = new NetworkInfo(networkType, 0,
1002 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1004 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001005 final NetworkCapabilities capabilities = new NetworkCapabilities();
1006 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1007 !info.isRoaming());
1008 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001009 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001011 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001012 return state;
1013 } else {
1014 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001016 }
1017
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1019 if (network == null) {
1020 return null;
1021 }
1022 synchronized (mNetworkForNetId) {
1023 return mNetworkForNetId.get(network.netId);
1024 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001025 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001027 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001028 synchronized (mVpns) {
1029 if (!mLockdownEnabled) {
1030 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001031 Vpn vpn = mVpns.get(user);
1032 if (vpn != null && vpn.appliesToUid(uid)) {
1033 return vpn.getUnderlyingNetworks();
1034 }
1035 }
1036 }
1037 return null;
1038 }
1039
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001041 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001042
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001043 final Network[] networks = getVpnUnderlyingNetworks(uid);
1044 if (networks != null) {
1045 // getUnderlyingNetworks() returns:
1046 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1047 // empty array => the VPN explicitly said "no default network".
1048 // non-empty array => the VPN specified one or more default networks; we use the
1049 // first one.
1050 if (networks.length > 0) {
1051 nai = getNetworkAgentInfoForNetwork(networks[0]);
1052 } else {
1053 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001054 }
1055 }
1056
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001058 return nai.getNetworkState();
1059 } else {
1060 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001061 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001062 }
1063
1064 /**
1065 * Check if UID should be blocked from using the network with the given LinkProperties.
1066 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001067 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1068 boolean ignoreBlocked) {
1069 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001070 if (ignoreBlocked) {
1071 return false;
1072 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001073 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001074 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1075 if (isSystem(uid)) {
1076 return false;
1077 }
Robin Lee17e61832016-05-09 13:46:28 +01001078 synchronized (mVpns) {
1079 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1080 if (vpn != null && vpn.isBlockingUid(uid)) {
1081 return true;
1082 }
1083 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001084 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001085 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 }
1087
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001088 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001089 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1090 return;
1091 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001092 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001093 synchronized (mBlockedAppUids) {
1094 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001095 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001096 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001097 blocked = false;
1098 } else {
1099 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001100 }
1101 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001102 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1103 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1104 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001105 }
1106
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001107 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001108 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1109 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001110 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001113 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1114
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001116 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 }
Hugo Benichi69744342017-11-27 10:57:16 +09001118 synchronized (mVpns) {
1119 if (mLockdownTracker != null) {
1120 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1121 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001122 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001123 }
1124
1125 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 * Return NetworkInfo for the active (i.e., connected) network interface.
1127 * It is assumed that at most one network is active at a time. If more
1128 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001129 * @return the info for the active network, or {@code null} if none is
1130 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 enforceAccessPermission();
1135 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1139 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141
Paul Jensen31a94f42015-02-13 14:18:39 -05001142 @Override
1143 public Network getActiveNetwork() {
1144 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001146 }
1147
1148 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001149 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001150 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001151 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001152 }
1153
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001154 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001155 final int user = UserHandle.getUserId(uid);
1156 int vpnNetId = NETID_UNSET;
1157 synchronized (mVpns) {
1158 final Vpn vpn = mVpns.get(user);
1159 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1160 }
1161 NetworkAgentInfo nai;
1162 if (vpnNetId != NETID_UNSET) {
1163 synchronized (mNetworkForNetId) {
1164 nai = mNetworkForNetId.get(vpnNetId);
1165 }
1166 if (nai != null) return nai.network;
1167 }
1168 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001169 if (nai != null
1170 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1171 nai = null;
1172 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001173 return nai != null ? nai.network : null;
1174 }
1175
Lorenzo Colitti18660282016-07-04 12:55:44 +09001176 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001177 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1178 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 final int uid = Binder.getCallingUid();
1180 NetworkState state = getUnfilteredActiveNetworkState(uid);
1181 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001182 }
1183
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001184 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001187 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001188 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001190 }
1191
1192 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 public NetworkInfo getNetworkInfo(int networkType) {
1194 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001195 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001196 if (getVpnUnderlyingNetworks(uid) != null) {
1197 // A VPN is active, so we may need to return one of its underlying networks. This
1198 // information is not available in LegacyTypeTracker, so we have to get it from
1199 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001200 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001201 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001202 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001203 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001204 }
1205 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001206 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001215 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001216 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001217 return state.networkInfo;
1218 } else {
1219 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001220 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001221 }
1222
1223 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 public NetworkInfo[] getAllNetworkInfo() {
1225 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001226 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001227 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1228 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001229 NetworkInfo info = getNetworkInfo(networkType);
1230 if (info != null) {
1231 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001234 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001237 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001238 public Network getNetworkForType(int networkType) {
1239 enforceAccessPermission();
1240 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001241 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1242 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001244 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001246 }
1247
1248 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001249 public Network[] getAllNetworks() {
1250 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001252 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001253 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001254 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001255 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001256 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001257 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001258 }
1259
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001260 @Override
1261 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1262 // The basic principle is: if an app's traffic could possibly go over a
1263 // network, without the app doing anything multinetwork-specific,
1264 // (hence, by "default"), then include that network's capabilities in
1265 // the array.
1266 //
1267 // In the normal case, app traffic only goes over the system's default
1268 // network connection, so that's the only network returned.
1269 //
1270 // With a VPN in force, some app traffic may go into the VPN, and thus
1271 // over whatever underlying networks the VPN specifies, while other app
1272 // traffic may go over the system default network (e.g.: a split-tunnel
1273 // VPN, or an app disallowed by the VPN), so the set of networks
1274 // returned includes the VPN's underlying networks and the system
1275 // default.
1276 enforceAccessPermission();
1277
1278 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1279
1280 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001281 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001282 if (nc != null) {
1283 result.put(nai.network, nc);
1284 }
1285
Hugo Benichi69744342017-11-27 10:57:16 +09001286 synchronized (mVpns) {
1287 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001288 Vpn vpn = mVpns.get(userId);
1289 if (vpn != null) {
1290 Network[] networks = vpn.getUnderlyingNetworks();
1291 if (networks != null) {
1292 for (Network network : networks) {
1293 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001294 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001295 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001296 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001297 }
1298 }
1299 }
1300 }
1301 }
1302 }
1303
1304 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1305 out = result.values().toArray(out);
1306 return out;
1307 }
1308
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001309 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001310 public boolean isNetworkSupported(int networkType) {
1311 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001312 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001313 }
1314
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001315 /**
1316 * Return LinkProperties for the active (i.e., connected) default
1317 * network interface. It is assumed that at most one default network
1318 * is active at a time. If more than one is active, it is indeterminate
1319 * which will be returned.
1320 * @return the ip properties for the active network, or {@code null} if
1321 * none is active
1322 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001323 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001324 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001325 enforceAccessPermission();
1326 final int uid = Binder.getCallingUid();
1327 NetworkState state = getUnfilteredActiveNetworkState(uid);
1328 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001329 }
1330
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001331 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001332 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001333 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001334 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1335 if (nai != null) {
1336 synchronized (nai) {
1337 return new LinkProperties(nai.linkProperties);
1338 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001339 }
1340 return null;
1341 }
1342
Robert Greenwalt12e67352014-05-13 21:41:06 -07001343 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001344 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001345 public LinkProperties getLinkProperties(Network network) {
1346 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001347 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1348 }
1349
1350 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1351 if (nai == null) {
1352 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001353 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001354 synchronized (nai) {
1355 return new LinkProperties(nai.linkProperties);
1356 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001357 }
1358
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001359 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001360 if (nai != null) {
1361 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001362 if (nai.networkCapabilities != null) {
Chalard Jeanb552c462018-02-21 18:43:54 +09001363 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1364 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001365 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001366 }
1367 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001368 return null;
1369 }
1370
1371 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001372 public NetworkCapabilities getNetworkCapabilities(Network network) {
1373 enforceAccessPermission();
1374 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1375 }
1376
Chalard Jeanb552c462018-02-21 18:43:54 +09001377 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1378 NetworkCapabilities nc, int callerPid, int callerUid) {
1379 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001380 return new NetworkCapabilities(nc).setUids(null);
1381 }
1382
Chalard Jeanb552c462018-02-21 18:43:54 +09001383 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1384 if (!checkSettingsPermission()) {
1385 nc.setSingleUid(Binder.getCallingUid());
1386 }
1387 }
1388
Chalard Jean26aa91a2018-03-20 19:13:57 +09001389 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1390 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1391 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1392 }
1393 }
1394
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001395 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001396 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001397 // Require internal since we're handing out IMSI details
1398 enforceConnectivityInternalPermission();
1399
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001400 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001401 for (Network network : getAllNetworks()) {
1402 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1403 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001404 // TODO (b/73321673) : NetworkState contains a copy of the
1405 // NetworkCapabilities, which may contain UIDs of apps to which the
1406 // network applies. Should the UIDs be cleared so as not to leak or
1407 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001408 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001409 }
1410 }
1411 return result.toArray(new NetworkState[result.size()]);
1412 }
1413
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001414 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001415 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001416 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001417 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1418 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1419 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001420 }
1421
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001422 @Override
1423 public boolean isActiveNetworkMetered() {
1424 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001425
Eric Enslenc81ef192018-02-07 18:03:53 -08001426 final int uid = Binder.getCallingUid();
1427 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001428 if (caps != null) {
1429 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1430 } else {
1431 // Always return the most conservative value
1432 return true;
1433 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001434 }
1435
Jeff Sharkey216c1812012-08-05 14:29:23 -07001436 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1437 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001438 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001439 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001440 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001441 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001442 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001443
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001444 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 * Ensure that a network route exists to deliver traffic to the specified
1446 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001447 * @param networkType the type of the network over which traffic to the
1448 * specified host is to be routed
1449 * @param hostAddress the IP address of the host to which the route is
1450 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 * @return {@code true} on success, {@code false} on failure
1452 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001453 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001454 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001456 if (mProtectedNetworks.contains(networkType)) {
1457 enforceConnectivityInternalPermission();
1458 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001459
Chad Brubakerc0234532014-02-14 13:24:29 -08001460 InetAddress addr;
1461 try {
1462 addr = InetAddress.getByAddress(hostAddress);
1463 } catch (UnknownHostException e) {
1464 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1465 return false;
1466 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001469 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 return false;
1471 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001472
1473 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1474 if (nai == null) {
1475 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1476 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1477 } else {
1478 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1479 }
1480 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001481 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001482
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001483 DetailedState netState;
1484 synchronized (nai) {
1485 netState = nai.networkInfo.getDetailedState();
1486 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001487
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001488 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001489 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001490 log("requestRouteToHostAddress on down network "
1491 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001492 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001493 }
1494 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001496
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001497 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001498 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001499 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001500 LinkProperties lp;
1501 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001502 synchronized (nai) {
1503 lp = nai.linkProperties;
1504 netId = nai.network.netId;
1505 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001506 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001507 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1508 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001509 } finally {
1510 Binder.restoreCallingIdentity(token);
1511 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001512 }
1513
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001514 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001515 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001516 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001517 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001518 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001519 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001520 if (bestRoute.getGateway().equals(addr)) {
1521 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001522 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001523 } else {
1524 // if we will connect to this through another route, add a direct route
1525 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001526 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001527 }
1528 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001529 if (DBG) log("Adding legacy route " + bestRoute +
1530 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001531 try {
1532 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1533 } catch (Exception e) {
1534 // never crash - catch them all
1535 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001536 return false;
1537 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001538 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
Jeff Sharkey75d31892018-01-18 22:01:59 +09001541 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001542 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001543 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001544 // TODO: notify UID when it has requested targeted updates
1545 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001546 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001547 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001548 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001549 if (restrictBackground) {
1550 log("onRestrictBackgroundChanged(true): disabling tethering");
1551 mTethering.untetherAll();
1552 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001553 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001554 };
1555
Robin Lee3b3dd942015-05-12 18:14:58 +01001556 /**
1557 * Require that the caller is either in the same user or has appropriate permission to interact
1558 * across users.
1559 *
1560 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1561 */
1562 private void enforceCrossUserPermission(int userId) {
1563 if (userId == UserHandle.getCallingUserId()) {
1564 // Not a cross-user call.
1565 return;
1566 }
1567 mContext.enforceCallingOrSelfPermission(
1568 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1569 "ConnectivityService");
1570 }
1571
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001572 private void enforceInternetPermission() {
1573 mContext.enforceCallingOrSelfPermission(
1574 android.Manifest.permission.INTERNET,
1575 "ConnectivityService");
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001579 mContext.enforceCallingOrSelfPermission(
1580 android.Manifest.permission.ACCESS_NETWORK_STATE,
1581 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
1584 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001585 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
Charles He36738632017-05-15 17:07:18 +01001588 private void enforceSettingsPermission() {
1589 mContext.enforceCallingOrSelfPermission(
1590 android.Manifest.permission.NETWORK_SETTINGS,
1591 "ConnectivityService");
1592 }
1593
Chalard Jeanb552c462018-02-21 18:43:54 +09001594 private boolean checkSettingsPermission() {
1595 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1596 android.Manifest.permission.NETWORK_SETTINGS);
1597 }
1598
1599 private boolean checkSettingsPermission(int pid, int uid) {
1600 return PERMISSION_GRANTED == mContext.checkPermission(
1601 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1602 }
1603
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001604 private void enforceTetherAccessPermission() {
1605 mContext.enforceCallingOrSelfPermission(
1606 android.Manifest.permission.ACCESS_NETWORK_STATE,
1607 "ConnectivityService");
1608 }
1609
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001610 private void enforceConnectivityInternalPermission() {
1611 mContext.enforceCallingOrSelfPermission(
1612 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1613 "ConnectivityService");
1614 }
1615
Hugo Benichi514da602016-07-19 15:59:27 +09001616 private void enforceConnectivityRestrictedNetworksPermission() {
1617 try {
1618 mContext.enforceCallingOrSelfPermission(
1619 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1620 "ConnectivityService");
1621 return;
1622 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1623 enforceConnectivityInternalPermission();
1624 }
1625
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001626 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001627 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001628 }
1629
Lorenzo Colitti18660282016-07-04 12:55:44 +09001630 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001631 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001632 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001633 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001634 }
1635
1636 private void sendInetConditionBroadcast(NetworkInfo info) {
1637 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1638 }
1639
Wink Saville628b0852011-08-04 15:01:58 -07001640 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001641 synchronized (mVpns) {
1642 if (mLockdownTracker != null) {
1643 info = new NetworkInfo(info);
1644 mLockdownTracker.augmentNetworkInfo(info);
1645 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001646 }
1647
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001648 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001649 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001650 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (info.isFailover()) {
1652 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1653 info.setFailover(false);
1654 }
1655 if (info.getReason() != null) {
1656 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1657 }
1658 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001659 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1660 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001662 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001663 return intent;
1664 }
1665
1666 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1667 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1668 }
1669
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001670 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001671 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1672 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1673 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001674 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001675 final long ident = Binder.clearCallingIdentity();
1676 try {
1677 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1678 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1679 } finally {
1680 Binder.restoreCallingIdentity(ident);
1681 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001682 }
1683
Mike Lockwood0f79b542009-08-14 14:18:49 -04001684 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001685 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001686 if (!mSystemReady) {
1687 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001688 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001689 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001690 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001691 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001692 }
1693
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001694 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001695 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001696 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001697 final NetworkInfo ni = intent.getParcelableExtra(
1698 ConnectivityManager.EXTRA_NETWORK_INFO);
1699 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1700 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1701 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001702 } else {
1703 BroadcastOptions opts = BroadcastOptions.makeBasic();
1704 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1705 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001706 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001707 final IBatteryStats bs = BatteryStatsService.getService();
1708 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001709 bs.noteConnectivityChanged(intent.getIntExtra(
1710 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1711 ni != null ? ni.getState().toString() : "?");
1712 } catch (RemoteException e) {
1713 }
Chad Brubakerac925012018-03-08 10:37:09 -08001714 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001715 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001716 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001717 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001718 } finally {
1719 Binder.restoreCallingIdentity(ident);
1720 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 }
1722 }
1723
1724 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001725 loadGlobalProxy();
1726
Hugo Benichi20035e02017-04-26 14:53:28 +09001727 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001728 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001729 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001730 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001731 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001732 }
1733 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001734 // load the global proxy at startup
1735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001736
Robin Lee244ce8e2016-01-05 18:03:46 +00001737 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1738 // for user to unlock device too.
1739 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001740
Erik Klineda4bfa82015-04-30 12:58:40 +09001741 // Configure whether mobile data is always on.
1742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1743
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001745
1746 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001751 *
1752 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001753 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001754 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1756 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001757
1758 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001760
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 if (networkAgent.networkCapabilities.hasTransport(
1762 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001763 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1764 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001765 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001766 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 } else if (networkAgent.networkCapabilities.hasTransport(
1768 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001769 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1770 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001771 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001773 } else {
1774 // do not track any other networks
1775 timeout = 0;
1776 }
1777
Robert Greenwalt7b816022014-04-18 15:25:25 -07001778 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001779 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001780 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001781 } catch (Exception e) {
1782 // You shall not crash!
1783 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001784 }
1785 }
1786 }
1787
1788 /**
1789 * Remove data activity tracking when network disconnects.
1790 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1792 final String iface = networkAgent.linkProperties.getInterfaceName();
1793 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001794
Robert Greenwalt7b816022014-04-18 15:25:25 -07001795 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1796 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001797 try {
1798 // the call fails silently if no idletimer setup for this interface
1799 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001800 } catch (Exception e) {
1801 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001802 }
1803 }
1804 }
1805
1806 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001807 * Reads the network specific MTU size from reources.
1808 * and set it on it's iface.
1809 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001810 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1811 final String iface = newLp.getInterfaceName();
1812 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001813 if (oldLp == null && mtu == 0) {
1814 // Silently ignore unset MTU value.
1815 return;
1816 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1818 if (VDBG) log("identical MTU - not setting");
1819 return;
1820 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001821 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001822 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 return;
1824 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001825
w1997615afd812014-08-05 15:18:11 -07001826 // Cannot set MTU without interface name
1827 if (TextUtils.isEmpty(iface)) {
1828 loge("Setting MTU size with null iface.");
1829 return;
1830 }
1831
Robert Greenwalt7b816022014-04-18 15:25:25 -07001832 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001833 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001834 mNetd.setMtu(iface, mtu);
1835 } catch (Exception e) {
1836 Slog.e(TAG, "exception in setMtu()" + e);
1837 }
1838 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001839
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001841 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1842
1843 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001844 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001845 protected MockableSystemProperties getSystemProperties() {
1846 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001847 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001848
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001849 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1850 if (isDefaultNetwork(nai) == false) {
1851 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001852 }
1853
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1855 String[] values = null;
1856 if (tcpBufferSizes != null) {
1857 values = tcpBufferSizes.split(",");
1858 }
1859
1860 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001861 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001862 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1863 values = tcpBufferSizes.split(",");
1864 }
1865
1866 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1867
1868 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001869 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001870
1871 final String prefix = "/sys/kernel/ipv4/tcp_";
1872 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1873 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1874 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1875 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1876 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1877 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1878 mCurrentTcpBufferSizes = tcpBufferSizes;
1879 } catch (IOException e) {
1880 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001881 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001882
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001883 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001884 Settings.Global.TCP_DEFAULT_INIT_RWND,
1885 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001886 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1887 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001888 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001889 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001890 }
1891
Robert Greenwalt562cc542014-05-15 18:07:26 -07001892 @Override
1893 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001894 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001895 NETWORK_RESTORE_DELAY_PROP_NAME);
1896 if(restoreDefaultNetworkDelayStr != null &&
1897 restoreDefaultNetworkDelayStr.length() != 0) {
1898 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001899 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001900 } catch (NumberFormatException e) {
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001903 // if the system property isn't set, use the value for the apn type
1904 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1905
1906 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1907 (mNetConfigs[networkType] != null)) {
1908 ret = mNetConfigs[networkType].restoreTime;
1909 }
1910 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
1912
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001913 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001914 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001915 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001916 }
1917 return false;
1918 }
1919
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001920 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1921 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1922 final long DIAG_TIME_MS = 5000;
1923 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1924 // Start gathering diagnostic information.
1925 netDiags.add(new NetworkDiagnostics(
1926 nai.network,
1927 new LinkProperties(nai.linkProperties), // Must be a copy.
1928 DIAG_TIME_MS));
1929 }
1930
1931 for (NetworkDiagnostics netDiag : netDiags) {
1932 pw.println();
1933 netDiag.waitForMeasurements();
1934 netDiag.dump(pw);
1935 }
1936 }
1937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001939 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001940 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1941 }
1942
1943 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001944 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001945 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001946 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001947
Erik Kline7747fd42017-05-12 16:52:48 +09001948 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001949 dumpNetworkDiagnostics(pw);
1950 return;
Erik Klineee363c42017-05-29 09:11:03 +09001951 } else if (argsContain(args, TETHERING_ARG)) {
1952 mTethering.dump(fd, pw, args);
1953 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001954 }
Erik Kline379747a2015-06-05 17:47:34 +09001955
Lorenzo Colittie3805462015-06-03 11:18:24 +09001956 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001957 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001958 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001959 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001960 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001961 pw.println();
1962
Paul Jensen85cf78e2015-06-25 13:25:07 -04001963 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001964 pw.print("Active default network: ");
1965 if (defaultNai == null) {
1966 pw.println("none");
1967 } else {
1968 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001970 pw.println();
1971
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001972 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001973 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001974 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1975 pw.println(nai.toString());
1976 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001977 pw.println(String.format(
1978 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1979 nai.numForegroundNetworkRequests(),
1980 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1981 nai.numBackgroundNetworkRequests(),
1982 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001983 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001984 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1985 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001986 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001987 pw.decreaseIndent();
1988 pw.println("Lingered:");
1989 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001990 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001991 pw.decreaseIndent();
1992 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001993 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001994 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001996
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001997 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001998 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001999 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2000 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002001 }
2002 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002003 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002004
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002005 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002006
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002007 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002008 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002009
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002010 pw.println();
2011 mKeepaliveTracker.dump(pw);
2012
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002013 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002014 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002015
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002016 pw.println();
2017 mMultipathPolicyTracker.dump(pw);
2018
Erik Kline7747fd42017-05-12 16:52:48 +09002019 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002020 pw.println();
2021 synchronized (mValidationLogs) {
2022 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002023 for (ValidationLog p : mValidationLogs) {
2024 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002025 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002026 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002027 pw.decreaseIndent();
2028 }
2029 }
Erik Kline7523eb32015-07-09 18:24:03 +09002030
2031 pw.println();
2032 pw.println("mNetworkRequestInfoLogs (most recent first):");
2033 pw.increaseIndent();
2034 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2035 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002036
2037 pw.println();
2038 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2039 pw.increaseIndent();
2040 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2041 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002042
2043 pw.println();
2044 pw.println("NetTransition WakeLock activity (most recent first):");
2045 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002046 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2047 pw.println("total releases: " + mTotalWakelockReleases);
2048 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2049 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2050 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2051 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2052 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2053 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002054 mWakelockLogs.reverseDump(fd, pw, args);
2055 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002059 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002060 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002061 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002062 if (officialNai != null && officialNai.equals(nai)) return true;
2063 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002064 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002065 " - " + nai);
2066 }
2067 return false;
2068 }
2069
Robert Greenwalt42acef32009-08-12 16:08:25 -07002070 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002071 private class NetworkStateTrackerHandler extends Handler {
2072 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002073 super(looper);
2074 }
2075
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002076 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002078 default:
2079 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002080 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002081 handleAsyncChannelHalfConnect(msg);
2082 break;
2083 }
2084 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2085 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2086 if (nai != null) nai.asyncChannel.disconnect();
2087 break;
2088 }
2089 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2090 handleAsyncChannelDisconnected(msg);
2091 break;
2092 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002093 }
2094 return true;
2095 }
2096
2097 private void maybeHandleNetworkAgentMessage(Message msg) {
2098 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2099 if (nai == null) {
2100 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002101 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002102 }
2103 return;
2104 }
2105
2106 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2109 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002110 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2111 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002112 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002113 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002114 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002115 break;
2116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002118 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 break;
2120 }
2121 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002122 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 updateNetworkInfo(nai, info);
2124 break;
2125 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002126 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002127 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002128 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002129 break;
2130 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002131 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002132 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2133 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002134 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002135 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002136 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002137 break;
2138 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002139 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002140 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2141 break;
2142 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002143 }
2144 }
2145
2146 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2147 switch (msg.what) {
2148 default:
2149 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002150 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002151 final NetworkAgentInfo nai;
2152 synchronized (mNetworkForNetId) {
2153 nai = mNetworkForNetId.get(msg.arg2);
2154 }
Erik Klinea24d4592018-01-11 21:07:29 +09002155 if (nai == null) break;
2156
2157 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2158 final boolean wasValidated = nai.lastValidated;
2159 final boolean wasDefault = isDefaultNetwork(nai);
2160
2161 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2162 ? (PrivateDnsConfig) msg.obj : null;
2163 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2164
2165 final boolean reevaluationRequired;
2166 final String logMsg;
2167 if (valid) {
2168 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2169 logMsg = (DBG && (privateDnsCfg != null))
2170 ? " with " + privateDnsCfg.toString() : "";
2171 } else {
2172 reevaluationRequired = false;
2173 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2174 ? " with redirect to " + redirectUrl : "";
2175 }
2176 if (DBG) {
2177 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2178 }
2179 // If there is a change in Private DNS configuration,
2180 // trigger reevaluation of the network to test it.
2181 if (reevaluationRequired) {
2182 nai.networkMonitor.sendMessage(
2183 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2184 break;
2185 }
2186 if (valid != nai.lastValidated) {
2187 if (wasDefault) {
2188 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2189 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002190 }
Erik Klinea24d4592018-01-11 21:07:29 +09002191 final int oldScore = nai.getCurrentScore();
2192 nai.lastValidated = valid;
2193 nai.everValidated |= valid;
2194 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2195 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2196 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2197 }
2198 updateInetCondition(nai);
2199 // Let the NetworkAgent know the state of its network
2200 Bundle redirectUrlBundle = new Bundle();
2201 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2202 nai.asyncChannel.sendMessage(
2203 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2204 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2205 0, redirectUrlBundle);
2206 if (wasValidated && !nai.lastValidated) {
2207 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002208 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 break;
2210 }
Paul Jensen869868be2014-05-15 10:33:05 -04002211 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002212 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002213 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002214 final NetworkAgentInfo nai;
2215 synchronized (mNetworkForNetId) {
2216 nai = mNetworkForNetId.get(netId);
2217 }
Calvin Onbe96da12016-10-11 15:10:46 -07002218 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002219 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002220 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002221 nai.lastCaptivePortalDetected = visible;
2222 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002223 if (nai.lastCaptivePortalDetected &&
2224 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2225 if (DBG) log("Avoiding captive portal network: " + nai.name());
2226 nai.asyncChannel.sendMessage(
2227 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2228 teardownUnneededNetwork(nai);
2229 break;
2230 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002231 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002232 }
2233 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002234 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002235 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002236 if (nai == null) {
2237 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2238 break;
2239 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002240 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002241 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002242 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002243 }
Paul Jensen869868be2014-05-15 10:33:05 -04002244 }
Paul Jensen869868be2014-05-15 10:33:05 -04002245 break;
2246 }
Erik Klinea24d4592018-01-11 21:07:29 +09002247 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2248 final NetworkAgentInfo nai;
2249 synchronized (mNetworkForNetId) {
2250 nai = mNetworkForNetId.get(msg.arg2);
2251 }
2252 if (nai == null) break;
2253
2254 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2255 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2256 if (nai.lastValidated && reevaluationRequired) {
2257 nai.networkMonitor.sendMessage(
2258 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2259 }
2260 break;
2261 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002262 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002263 return true;
2264 }
2265
Calvin Onbe96da12016-10-11 15:10:46 -07002266 private int getCaptivePortalMode() {
2267 return Settings.Global.getInt(mContext.getContentResolver(),
2268 Settings.Global.CAPTIVE_PORTAL_MODE,
2269 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2270 }
2271
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002272 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2273 switch (msg.what) {
2274 default:
2275 return false;
2276 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2277 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2278 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2279 handleLingerComplete(nai);
2280 }
2281 break;
2282 }
2283 }
2284 return true;
2285 }
2286
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002287 @Override
2288 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002289 if (!maybeHandleAsyncChannelMessage(msg) &&
2290 !maybeHandleNetworkMonitorMessage(msg) &&
2291 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002292 maybeHandleNetworkAgentMessage(msg);
2293 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002294 }
2295 }
2296
Erik Klinea24d4592018-01-11 21:07:29 +09002297 private void handlePrivateDnsSettingsChanged() {
2298 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2299
2300 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2301 // Private DNS only ever applies to networks that might provide
2302 // Internet access and therefore also require validation.
2303 if (!NetworkMonitor.isValidationRequired(
2304 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2305 continue;
2306 }
2307
2308 // Notify the NetworkMonitor thread in case it needs to cancel or
2309 // schedule DNS resolutions. If a DNS resolution is required the
2310 // result will be sent back to us.
2311 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2312
2313 if (!cfg.inStrictMode()) {
2314 // No strict mode hostname DNS resolution needed, so just update
2315 // DNS settings directly. In opportunistic and "off" modes this
2316 // just reprograms netd with the network-supplied DNS servers
2317 // (and of course the boolean of whether or not to attempt TLS).
2318 //
2319 // TODO: Consider code flow parity with strict mode, i.e. having
2320 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2321 // performing this call at that time.
2322 updatePrivateDns(nai, cfg);
2323 }
2324 }
2325 }
2326
2327 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2328 final boolean reevaluationRequired = true;
2329 final boolean dontReevaluate = false;
2330
2331 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2332 updateDnses(nai.linkProperties, null, nai.network.netId);
2333
2334 if (newCfg == null) {
2335 if (oldCfg == null) return dontReevaluate;
2336 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2337 }
2338
2339 if (oldCfg == null) {
2340 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2341 }
2342
2343 if (oldCfg.useTls != newCfg.useTls) {
2344 return reevaluationRequired;
2345 }
2346
2347 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2348 return reevaluationRequired;
2349 }
2350
2351 return dontReevaluate;
2352 }
2353
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002354 private void updateLingerState(NetworkAgentInfo nai, long now) {
2355 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2356 // 2. If the network was lingering and there are now requests, unlinger it.
2357 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2358 // one lingered request, start lingering.
2359 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002360 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002361 if (DBG) log("Unlingering " + nai.name());
2362 nai.unlinger();
2363 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002364 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002365 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002366 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002367 nai.linger();
2368 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2369 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2370 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002371 }
2372
Robert Greenwalt7b816022014-04-18 15:25:25 -07002373 private void handleAsyncChannelHalfConnect(Message msg) {
2374 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002375 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2377 if (VDBG) log("NetworkFactory connected");
2378 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002379 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002380 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002381 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002382 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002383 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002384 }
2385 } else {
2386 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002387 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002388 }
2389 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2390 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2391 if (VDBG) log("NetworkAgent connected");
2392 // A network agent has requested a connection. Establish the connection.
2393 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2394 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2395 } else {
2396 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002397 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002398 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002399 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002400 synchronized (mNetworkForNetId) {
2401 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002402 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002403 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002404 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002405 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002406 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 }
2408 }
2409 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002410
Robert Greenwalt7b816022014-04-18 15:25:25 -07002411 private void handleAsyncChannelDisconnected(Message msg) {
2412 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2413 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002414 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002415 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002416 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002417 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002418 // TODO - if we move the logic to the network agent (have them disconnect
2419 // because they lost all their requests or because their score isn't good)
2420 // then they would disconnect organically, report their new state and then
2421 // disconnect the channel.
2422 if (nai.networkInfo.isConnected()) {
2423 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2424 null, null);
2425 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002426 final boolean wasDefault = isDefaultNetwork(nai);
2427 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002428 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002429 // Log default network disconnection before required book-keeping.
2430 // Let rematchAllNetworksAndRequests() below record a new default network event
2431 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2432 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002433 long now = SystemClock.elapsedRealtime();
2434 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002435 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002436 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002437 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2438 // by other networks that are already connected. Perhaps that can be done by
2439 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2440 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002441 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002442 mKeepaliveTracker.handleStopAllKeepalives(nai,
2443 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002444 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2445 // Disable wakeup packet monitoring for each interface.
2446 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2447 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002448 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002449 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002450 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002451 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002452 // Remove the NetworkAgent, but don't mark the netId as
2453 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002454 mNetworkForNetId.remove(nai.network.netId);
2455 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002456 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002457 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2458 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002459 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002460 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002461 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002462 sendUpdatedScoreToFactories(request, 0);
2463 }
2464 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002465 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002466 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002467 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002468 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002469 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002470 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002471 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002472 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002473 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002474 if (nai.created) {
2475 // Tell netd to clean up the configuration for this network
2476 // (routing rules, DNS, etc).
2477 // This may be slow as it requires a lot of netd shelling out to ip and
2478 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2479 // after we've rematched networks with requests which should make a potential
2480 // fallback network the default or requested a new network from the
2481 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2482 // long time.
2483 try {
2484 mNetd.removeNetwork(nai.network.netId);
2485 } catch (Exception e) {
2486 loge("Exception removing network: " + e);
2487 }
Erik Klinea24d4592018-01-11 21:07:29 +09002488 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002489 }
2490 synchronized (mNetworkForNetId) {
2491 mNetIdInUse.delete(nai.network.netId);
2492 }
2493 } else {
2494 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2495 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002496 }
2497 }
2498
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002499 // If this method proves to be too slow then we can maintain a separate
2500 // pendingIntent => NetworkRequestInfo map.
2501 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2502 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2503 Intent intent = pendingIntent.getIntent();
2504 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2505 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2506 if (existingPendingIntent != null &&
2507 existingPendingIntent.getIntent().filterEquals(intent)) {
2508 return entry.getValue();
2509 }
2510 }
2511 return null;
2512 }
2513
2514 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2515 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2516
2517 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2518 if (existingRequest != null) { // remove the existing request.
2519 if (DBG) log("Replacing " + existingRequest.request + " with "
2520 + nri.request + " because their intents matched.");
2521 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2522 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002523 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002524 }
2525
Erik Klineda4bfa82015-04-30 12:58:40 +09002526 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002527 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002528 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002529 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002530 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002531 if (nri.request.networkCapabilities.hasSignalStrength() &&
2532 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2533 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002534 }
2535 }
2536 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002537 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002538 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002539 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002540 }
2541 }
2542
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002543 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2544 int callingUid) {
2545 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2546 if (nri != null) {
2547 handleReleaseNetworkRequest(nri.request, callingUid);
2548 }
2549 }
2550
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002551 // Determines whether the network is the best (or could become the best, if it validated), for
2552 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2553 // on the value of reason:
2554 //
2555 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2556 // then it should be torn down.
2557 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2558 // then it should be lingered.
2559 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2560 final int numRequests;
2561 switch (reason) {
2562 case TEARDOWN:
2563 numRequests = nai.numRequestNetworkRequests();
2564 break;
2565 case LINGER:
2566 numRequests = nai.numForegroundNetworkRequests();
2567 break;
2568 default:
2569 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2570 return true;
2571 }
2572
2573 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002574 return false;
2575 }
Paul Jensene0988542015-06-25 15:30:08 -04002576 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002577 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2578 // Background requests don't affect lingering.
2579 continue;
2580 }
2581
Paul Jensene0988542015-06-25 15:30:08 -04002582 // If this Network is already the highest scoring Network for a request, or if
2583 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002584 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002585 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002586 // Note that this catches two important cases:
2587 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2588 // is currently satisfying the request. This is desirable when
2589 // cellular ends up validating but WiFi does not.
2590 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002591 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002592 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002593 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002594 nai.getCurrentScoreAsValidated())) {
2595 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002596 }
2597 }
Paul Jensene0988542015-06-25 15:30:08 -04002598 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002599 }
2600
Erik Klineacdd6392016-07-07 16:50:58 +09002601 private NetworkRequestInfo getNriForAppRequest(
2602 NetworkRequest request, int callingUid, String requestedOperation) {
2603 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2604
Robert Greenwalt9258c642014-03-26 16:47:06 -07002605 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002606 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002607 log(String.format("UID %d attempted to %s for unowned request %s",
2608 callingUid, requestedOperation, nri));
2609 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002610 }
Erik Klineacdd6392016-07-07 16:50:58 +09002611 }
2612
2613 return nri;
2614 }
2615
Erik Kline57faba92015-11-25 12:49:38 +09002616 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002617 if (mNetworkRequests.get(nri.request) == null) {
2618 return;
Erik Kline57faba92015-11-25 12:49:38 +09002619 }
Hugo Benichicd952782017-09-20 11:20:14 +09002620 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002621 return;
2622 }
2623 if (VDBG || (DBG && nri.request.isRequest())) {
2624 log("releasing " + nri.request + " (timeout)");
2625 }
2626 handleRemoveNetworkRequest(nri);
2627 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002628 }
2629
Erik Klineacdd6392016-07-07 16:50:58 +09002630 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002631 final NetworkRequestInfo nri =
2632 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2633 if (nri == null) {
2634 return;
Erik Kline57faba92015-11-25 12:49:38 +09002635 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002636 if (VDBG || (DBG && nri.request.isRequest())) {
2637 log("releasing " + nri.request + " (release request)");
2638 }
2639 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002640 }
Erik Klineacdd6392016-07-07 16:50:58 +09002641
Hugo Benichidba33db2017-03-23 22:40:44 +09002642 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002643 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002644 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002645
Erik Klineacdd6392016-07-07 16:50:58 +09002646 synchronized (mUidToNetworkRequestCount) {
2647 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2648 if (requests < 1) {
2649 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2650 nri.mUid);
2651 } else if (requests == 1) {
2652 mUidToNetworkRequestCount.removeAt(
2653 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2654 } else {
2655 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2656 }
2657 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002658
Erik Klineacdd6392016-07-07 16:50:58 +09002659 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2660 if (nri.request.isRequest()) {
2661 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002662 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002663 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002664 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002665 nai.removeRequest(nri.request.requestId);
2666 if (VDBG) {
2667 log(" Removing from current network " + nai.name() +
2668 ", leaving " + nai.numNetworkRequests() + " requests.");
2669 }
2670 // If there are still lingered requests on this network, don't tear it down,
2671 // but resume lingering instead.
2672 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002673 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002674 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2675 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002676 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002677 wasKept = true;
2678 }
Hugo Benichicd952782017-09-20 11:20:14 +09002679 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002680 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2681 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002682 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002683 }
Erik Klineacdd6392016-07-07 16:50:58 +09002684 }
2685
2686 // TODO: remove this code once we know that the Slog.wtf is never hit.
2687 //
2688 // Find all networks that are satisfying this request and remove the request
2689 // from their request lists.
2690 // TODO - it's my understanding that for a request there is only a single
2691 // network satisfying it, so this loop is wasteful
2692 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2693 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2694 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2695 otherNai.name() + ", but mNetworkAgentInfos says " +
2696 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002697 }
2698 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002699
Erik Klineacdd6392016-07-07 16:50:58 +09002700 // Maintain the illusion. When this request arrived, we might have pretended
2701 // that a network connected to serve it, even though the network was already
2702 // connected. Now that this request has gone away, we might have to pretend
2703 // that the network disconnected. LegacyTypeTracker will generate that
2704 // phantom disconnect for this type.
2705 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2706 boolean doRemove = true;
2707 if (wasKept) {
2708 // check if any of the remaining requests for this network are for the
2709 // same legacy type - if so, don't remove the nai
2710 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2711 NetworkRequest otherRequest = nai.requestAt(i);
2712 if (otherRequest.legacyType == nri.request.legacyType &&
2713 otherRequest.isRequest()) {
2714 if (DBG) log(" still have other legacy request - leaving");
2715 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002716 }
2717 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002718 }
2719
Erik Klineacdd6392016-07-07 16:50:58 +09002720 if (doRemove) {
2721 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002722 }
2723 }
Erik Klineacdd6392016-07-07 16:50:58 +09002724
2725 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2726 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2727 nri.request);
2728 }
2729 } else {
2730 // listens don't have a singular affectedNetwork. Check all networks to see
2731 // if this listen request applies and remove it.
2732 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2733 nai.removeRequest(nri.request.requestId);
2734 if (nri.request.networkCapabilities.hasSignalStrength() &&
2735 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2736 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2737 }
2738 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002739 }
2740 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002741
Lorenzo Colitti18660282016-07-04 12:55:44 +09002742 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002743 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2744 enforceConnectivityInternalPermission();
2745 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002746 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002747 }
2748
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002749 @Override
2750 public void setAvoidUnvalidated(Network network) {
2751 enforceConnectivityInternalPermission();
2752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2753 }
2754
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002755 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2756 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2757 " accept=" + accept + " always=" + always);
2758
2759 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2760 if (nai == null) {
2761 // Nothing to do.
2762 return;
2763 }
2764
2765 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002766 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002767 return;
2768 }
2769
2770 if (!nai.networkMisc.explicitlySelected) {
2771 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2772 }
2773
2774 if (accept != nai.networkMisc.acceptUnvalidated) {
2775 int oldScore = nai.getCurrentScore();
2776 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002777 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002778 sendUpdatedScoreToFactories(nai);
2779 }
2780
2781 if (always) {
2782 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002783 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784 }
2785
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002786 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002787 // Tell the NetworkAgent to not automatically reconnect to the network.
2788 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2789 // Teardown the nework.
2790 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002791 }
2792
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002793 }
2794
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002795 private void handleSetAvoidUnvalidated(Network network) {
2796 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2797 if (nai == null || nai.lastValidated) {
2798 // Nothing to do. The network either disconnected or revalidated.
2799 return;
2800 }
2801 if (!nai.avoidUnvalidated) {
2802 int oldScore = nai.getCurrentScore();
2803 nai.avoidUnvalidated = true;
2804 rematchAllNetworksAndRequests(nai, oldScore);
2805 sendUpdatedScoreToFactories(nai);
2806 }
2807 }
2808
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002809 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002810 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002811 mHandler.sendMessageDelayed(
2812 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2813 PROMPT_UNVALIDATED_DELAY_MS);
2814 }
2815
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002816 @Override
2817 public void startCaptivePortalApp(Network network) {
2818 enforceConnectivityInternalPermission();
2819 mHandler.post(() -> {
2820 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2821 if (nai == null) return;
2822 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2823 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2824 });
2825 }
2826
Hugo Benichic8e9e122016-09-14 23:23:08 +00002827 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002828 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002829 }
2830
Erik Kline065ab6e2016-10-02 18:02:14 +09002831 private void rematchForAvoidBadWifiUpdate() {
2832 rematchAllNetworksAndRequests(null, 0);
2833 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2834 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2835 sendUpdatedScoreToFactories(nai);
2836 }
2837 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002838 }
2839
Erik Kline065ab6e2016-10-02 18:02:14 +09002840 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002841 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002842 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002843 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002844 if (!configRestrict) {
2845 pw.println("Bad Wi-Fi avoidance: unrestricted");
2846 return;
2847 }
2848
2849 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2850 pw.increaseIndent();
2851 pw.println("Config restrict: " + configRestrict);
2852
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002853 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002854 String description;
2855 // Can't use a switch statement because strings are legal case labels, but null is not.
2856 if ("0".equals(value)) {
2857 description = "get stuck";
2858 } else if (value == null) {
2859 description = "prompt";
2860 } else if ("1".equals(value)) {
2861 description = "avoid";
2862 } else {
2863 description = value + " (?)";
2864 }
2865 pw.println("User setting: " + description);
2866 pw.println("Network overrides:");
2867 pw.increaseIndent();
2868 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2869 if (nai.avoidUnvalidated) {
2870 pw.println(nai.name());
2871 }
2872 }
2873 pw.decreaseIndent();
2874 pw.decreaseIndent();
2875 }
2876
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002877 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2878 final String action;
2879 switch (type) {
2880 case NO_INTERNET:
2881 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2882 break;
2883 case LOST_INTERNET:
2884 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2885 break;
2886 default:
2887 Slog.wtf(TAG, "Unknown notification type " + type);
2888 return;
2889 }
2890
2891 Intent intent = new Intent(action);
2892 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2893 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2894 intent.setClassName("com.android.settings",
2895 "com.android.settings.wifi.WifiNoInternetDialog");
2896
2897 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2898 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2899 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2900 }
2901
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002902 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002903 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002904 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2905
2906 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2907 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002908 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002909 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002910 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2911 return;
2912 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002913 showValidationNotification(nai, NotificationType.NO_INTERNET);
2914 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002915
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002916 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2917 NetworkCapabilities nc = nai.networkCapabilities;
2918 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002919
Erik Kline065ab6e2016-10-02 18:02:14 +09002920 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002921 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002922 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2923 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002924 }
2925
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002926 @Override
2927 public int getMultipathPreference(Network network) {
2928 enforceAccessPermission();
2929
2930 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002931 if (nai != null && nai.networkCapabilities
2932 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002933 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2934 }
2935
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002936 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2937 if (networkPreference != null) {
2938 return networkPreference;
2939 }
2940
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002941 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2942 }
2943
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002944 private class InternalHandler extends Handler {
2945 public InternalHandler(Looper looper) {
2946 super(looper);
2947 }
2948
2949 @Override
2950 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002951 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002952 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002953 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002954 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002955 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002956 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002957 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002959 break;
2960 }
Jason Monkdecd2952013-10-10 14:02:51 -04002961 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002962 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002963 break;
2964 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002965 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002966 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2967 break;
2968 }
2969 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2970 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002971 break;
2972 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002973 case EVENT_REGISTER_NETWORK_AGENT: {
2974 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2975 break;
2976 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002977 case EVENT_REGISTER_NETWORK_REQUEST:
2978 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002979 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002980 break;
2981 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002982 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2983 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002984 handleRegisterNetworkRequestWithIntent(msg);
2985 break;
2986 }
Erik Kline57faba92015-11-25 12:49:38 +09002987 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2988 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2989 handleTimedOutNetworkRequest(nri);
2990 break;
2991 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002992 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2993 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2994 break;
2995 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002996 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002997 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002998 break;
2999 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003000 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003001 Network network = (Network) msg.obj;
3002 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003003 break;
3004 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003005 case EVENT_SET_AVOID_UNVALIDATED: {
3006 handleSetAvoidUnvalidated((Network) msg.obj);
3007 break;
3008 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003009 case EVENT_PROMPT_UNVALIDATED: {
3010 handlePromptUnvalidated((Network) msg.obj);
3011 break;
3012 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003013 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3014 handleMobileDataAlwaysOn();
3015 break;
3016 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003017 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3018 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3019 mKeepaliveTracker.handleStartKeepalive(msg);
3020 break;
3021 }
3022 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3023 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3024 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3025 int slot = msg.arg1;
3026 int reason = msg.arg2;
3027 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3028 break;
3029 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003030 case EVENT_SYSTEM_READY: {
3031 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3032 nai.networkMonitor.systemReady = true;
3033 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003034 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003035 break;
3036 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003037 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003038 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003039 break;
3040 }
Erik Klinea24d4592018-01-11 21:07:29 +09003041 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3042 handlePrivateDnsSettingsChanged();
3043 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045 }
3046 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003047
3048 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003049 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003050 public int tether(String iface, String callerPkg) {
3051 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003052 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003053 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003054 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003055 } else {
3056 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3057 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003058 }
3059
3060 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003061 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003062 public int untether(String iface, String callerPkg) {
3063 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003064
3065 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003066 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003067 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003068 } else {
3069 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3070 }
3071 }
3072
3073 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003074 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003075 public int getLastTetherError(String iface) {
3076 enforceTetherAccessPermission();
3077
3078 if (isTetheringSupported()) {
3079 return mTethering.getLastTetherError(iface);
3080 } else {
3081 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3082 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003083 }
3084
3085 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003086 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003087 public String[] getTetherableUsbRegexs() {
3088 enforceTetherAccessPermission();
3089 if (isTetheringSupported()) {
3090 return mTethering.getTetherableUsbRegexs();
3091 } else {
3092 return new String[0];
3093 }
3094 }
3095
Lorenzo Colitti18660282016-07-04 12:55:44 +09003096 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003097 public String[] getTetherableWifiRegexs() {
3098 enforceTetherAccessPermission();
3099 if (isTetheringSupported()) {
3100 return mTethering.getTetherableWifiRegexs();
3101 } else {
3102 return new String[0];
3103 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003104 }
3105
Lorenzo Colitti18660282016-07-04 12:55:44 +09003106 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003107 public String[] getTetherableBluetoothRegexs() {
3108 enforceTetherAccessPermission();
3109 if (isTetheringSupported()) {
3110 return mTethering.getTetherableBluetoothRegexs();
3111 } else {
3112 return new String[0];
3113 }
3114 }
3115
Lorenzo Colitti18660282016-07-04 12:55:44 +09003116 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003117 public int setUsbTethering(boolean enable, String callerPkg) {
3118 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003119 if (isTetheringSupported()) {
3120 return mTethering.setUsbTethering(enable);
3121 } else {
3122 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3123 }
3124 }
3125
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003126 // TODO - move iface listing, queries, etc to new module
3127 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003128 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003129 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003130 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003131 return mTethering.getTetherableIfaces();
3132 }
3133
Lorenzo Colitti18660282016-07-04 12:55:44 +09003134 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003135 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003136 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003137 return mTethering.getTetheredIfaces();
3138 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003139
Lorenzo Colitti18660282016-07-04 12:55:44 +09003140 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003141 public String[] getTetheringErroredIfaces() {
3142 enforceTetherAccessPermission();
3143 return mTethering.getErroredIfaces();
3144 }
3145
Lorenzo Colitti18660282016-07-04 12:55:44 +09003146 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003147 public String[] getTetheredDhcpRanges() {
3148 enforceConnectivityInternalPermission();
3149 return mTethering.getTetheredDhcpRanges();
3150 }
3151
Udam Saini0e94c362017-06-07 12:06:28 -07003152 @Override
3153 public boolean isTetheringSupported(String callerPkg) {
3154 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3155 return isTetheringSupported();
3156 }
3157
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003158 // if ro.tether.denied = true we default to no tethering
3159 // gservices could set the secure setting to 1 though to enable it on a build where it
3160 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003161 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003162 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3163 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3164 Settings.Global.TETHER_SUPPORTED, defaultVal));
3165 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003166 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003167
3168 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3169 boolean adminUser = false;
3170 final long token = Binder.clearCallingIdentity();
3171 try {
3172 adminUser = mUserManager.isAdminUser();
3173 } finally {
3174 Binder.restoreCallingIdentity(token);
3175 }
3176
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003177 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003178 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003179
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003180 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003181 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3182 String callerPkg) {
3183 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003184 if (!isTetheringSupported()) {
3185 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3186 return;
3187 }
3188 mTethering.startTethering(type, receiver, showProvisioningUi);
3189 }
3190
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003191 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003192 public void stopTethering(int type, String callerPkg) {
3193 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003194 mTethering.stopTethering(type);
3195 }
3196
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003197 // Called when we lose the default network and have no replacement yet.
3198 // This will automatically be cleared after X seconds or a new default network
3199 // becomes CONNECTED, whichever happens first. The timer is started by the
3200 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003201 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003202 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003203 if (mNetTransitionWakeLock.isHeld()) {
3204 return;
3205 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003206 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003207 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3208 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003209 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003210 mWakelockLogs.log("ACQUIRE for " + forWhom);
3211 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3212 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003213 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003214
Hugo Benichi4c31b342017-03-30 23:18:10 +09003215 // Called when we gain a new default network to release the network transition wakelock in a
3216 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3217 // message is cancelled.
3218 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003219 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003220 if (!mNetTransitionWakeLock.isHeld()) {
3221 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003222 }
3223 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003224 // Cancel self timeout on wakelock hold.
3225 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3226 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3227 mHandler.sendMessageDelayed(msg, 1000);
3228 }
3229
3230 // Called when either message of ensureNetworkTransitionWakelock or
3231 // scheduleReleaseNetworkTransitionWakelock is processed.
3232 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3233 String event = eventName(eventId);
3234 synchronized (this) {
3235 if (!mNetTransitionWakeLock.isHeld()) {
3236 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3237 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3238 return;
3239 }
3240 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003241 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3242 mTotalWakelockDurationMs += lockDuration;
3243 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3244 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003245 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003246 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003247 }
3248
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003249 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003250 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003251 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003252 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003253 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003254 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003255 }
3256
Lorenzo Colitti18660282016-07-04 12:55:44 +09003257 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003258 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003259 enforceAccessPermission();
3260 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003261 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003262 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003263 mHandler.sendMessage(
3264 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3265 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003266
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003267 private void handleReportNetworkConnectivity(
3268 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003269 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003270 if (network == null) {
3271 nai = getDefaultNetwork();
3272 } else {
3273 nai = getNetworkAgentInfoForNetwork(network);
3274 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003275 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3276 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3277 return;
3278 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003279 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003280 if (hasConnectivity == nai.lastValidated) {
3281 return;
3282 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003283 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003284 int netid = nai.network.netId;
3285 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003286 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003287 // Validating a network that has not yet connected could result in a call to
3288 // rematchNetworkAndRequests() which is not meant to work on such networks.
3289 if (!nai.everConnected) {
3290 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003291 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003292 LinkProperties lp = getLinkProperties(nai);
3293 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3294 return;
3295 }
3296 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003297 }
3298
Paul Jensencee9b512015-05-06 07:32:40 -04003299 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003300 // this information is already available as a world read/writable jvm property
3301 // so this API change wouldn't have a benifit. It also breaks the passing
3302 // of proxy info to all the JVMs.
3303 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003304 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003305 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003306 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3307 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003308 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003309 }
3310
Lorenzo Colitti18660282016-07-04 12:55:44 +09003311 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003312 public ProxyInfo getProxyForNetwork(Network network) {
3313 if (network == null) return getDefaultProxy();
3314 final ProxyInfo globalProxy = getGlobalProxy();
3315 if (globalProxy != null) return globalProxy;
3316 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3317 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3318 // caller may not have.
3319 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3320 if (nai == null) return null;
3321 synchronized (nai) {
3322 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3323 if (proxyInfo == null) return null;
3324 return new ProxyInfo(proxyInfo);
3325 }
3326 }
3327
Paul Jensene0bef712014-12-10 15:12:18 -05003328 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3329 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3330 // proxy is null then there is no proxy in place).
3331 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3332 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3333 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3334 proxy = null;
3335 }
3336 return proxy;
3337 }
3338
3339 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3340 // better for determining if a new proxy broadcast is necessary:
3341 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3342 // avoid unnecessary broadcasts.
3343 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3344 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3345 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3346 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3347 // all set.
3348 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3349 a = canonicalizeProxyInfo(a);
3350 b = canonicalizeProxyInfo(b);
3351 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3352 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3353 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3354 }
3355
Jason Monk207900c2014-04-25 15:00:09 -04003356 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003357 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003358
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003359 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003360 if (proxyProperties == mGlobalProxy) return;
3361 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3362 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3363
3364 String host = "";
3365 int port = 0;
3366 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003367 String pacFileUrl = "";
3368 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003369 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003370 if (!proxyProperties.isValid()) {
3371 if (DBG)
3372 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3373 return;
3374 }
Jason Monk207900c2014-04-25 15:00:09 -04003375 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003376 host = mGlobalProxy.getHost();
3377 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003378 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003379 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003380 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003381 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003382 } else {
3383 mGlobalProxy = null;
3384 }
3385 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003386 final long token = Binder.clearCallingIdentity();
3387 try {
3388 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3389 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3390 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3391 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003392 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003393 } finally {
3394 Binder.restoreCallingIdentity(token);
3395 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396
Jason Monkcf0f97a2014-10-02 15:39:38 -04003397 if (mGlobalProxy == null) {
3398 proxyProperties = mDefaultProxy;
3399 }
3400 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 }
3403
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003404 private void loadGlobalProxy() {
3405 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003406 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3407 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3408 String exclList = Settings.Global.getString(res,
3409 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003410 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3411 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003412 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003413 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003414 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003415 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003416 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003417 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003418 if (!proxyProperties.isValid()) {
3419 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3420 return;
3421 }
3422
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003423 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003424 mGlobalProxy = proxyProperties;
3425 }
3426 }
3427 }
3428
Jason Monk207900c2014-04-25 15:00:09 -04003429 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003430 // this information is already available as a world read/writable jvm property
3431 // so this API change wouldn't have a benifit. It also breaks the passing
3432 // of proxy info to all the JVMs.
3433 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003434 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003435 return mGlobalProxy;
3436 }
3437 }
3438
Jason Monk207900c2014-04-25 15:00:09 -04003439 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003440 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003441 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003442 proxy = null;
3443 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003444 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003445 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003446 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003447 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003448 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3449 return;
3450 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003451
3452 // This call could be coming from the PacManager, containing the port of the local
3453 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3454 // global (to get the correct local port), and send a broadcast.
3455 // TODO: Switch PacManager to have its own message to send back rather than
3456 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003457 if ((mGlobalProxy != null) && (proxy != null)
3458 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003459 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3460 mGlobalProxy = proxy;
3461 sendProxyBroadcast(mGlobalProxy);
3462 return;
3463 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003464 mDefaultProxy = proxy;
3465
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003466 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003467 if (!mDefaultProxyDisabled) {
3468 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 }
3470 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003471 }
3472
Paul Jensene0bef712014-12-10 15:12:18 -05003473 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3474 // This method gets called when any network changes proxy, but the broadcast only ever contains
3475 // the default proxy (even if it hasn't changed).
3476 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3477 // world where an app might be bound to a non-default network.
3478 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3479 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3480 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3481
3482 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3483 sendProxyBroadcast(getDefaultProxy());
3484 }
3485 }
3486
Robert Greenwalt434203a2010-10-11 16:00:27 -07003487 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003488 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3489 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 if (!TextUtils.isEmpty(proxy)) {
3491 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003492 if (data.length == 0) {
3493 return;
3494 }
3495
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 String proxyHost = data[0];
3497 int proxyPort = 8080;
3498 if (data.length > 1) {
3499 try {
3500 proxyPort = Integer.parseInt(data[1]);
3501 } catch (NumberFormatException e) {
3502 return;
3503 }
3504 }
Jason Monk207900c2014-04-25 15:00:09 -04003505 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003506 setGlobalProxy(p);
3507 }
3508 }
3509
Jason Monk207900c2014-04-25 15:00:09 -04003510 private void sendProxyBroadcast(ProxyInfo proxy) {
3511 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003512 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003513 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003514 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003515 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3516 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003517 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003518 final long ident = Binder.clearCallingIdentity();
3519 try {
3520 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3521 } finally {
3522 Binder.restoreCallingIdentity(ident);
3523 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003524 }
3525
3526 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003527 final private HashMap<Uri, Integer> mUriEventMap;
3528 final private Context mContext;
3529 final private Handler mHandler;
3530
3531 SettingsObserver(Context context, Handler handler) {
3532 super(null);
3533 mUriEventMap = new HashMap<Uri, Integer>();
3534 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003535 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003536 }
3537
Erik Klineda4bfa82015-04-30 12:58:40 +09003538 void observe(Uri uri, int what) {
3539 mUriEventMap.put(uri, what);
3540 final ContentResolver resolver = mContext.getContentResolver();
3541 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003542 }
3543
3544 @Override
3545 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003546 Slog.wtf(TAG, "Should never be reached.");
3547 }
3548
3549 @Override
3550 public void onChange(boolean selfChange, Uri uri) {
3551 final Integer what = mUriEventMap.get(uri);
3552 if (what != null) {
3553 mHandler.obtainMessage(what.intValue()).sendToTarget();
3554 } else {
3555 loge("No matching event to send for URI=" + uri);
3556 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003557 }
3558 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003559
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003560 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003561 Slog.d(TAG, s);
3562 }
3563
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003564 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003565 Slog.e(TAG, s);
3566 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003567
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003568 private static void loge(String s, Throwable t) {
3569 Slog.e(TAG, s, t);
3570 }
3571
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003572 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003573 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003574 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3575 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3576 *
3577 * @param oldPackage Package name of the application which currently controls VPN, which will
3578 * be replaced. If there is no such application, this should should either be
3579 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3580 * @param newPackage Package name of the application which should gain control of VPN, or
3581 * {@code null} to disable.
3582 * @param userId User for whom to prepare the new VPN.
3583 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003584 * @hide
3585 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003586 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003587 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3588 int userId) {
3589 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003590
Hugo Benichi20035e02017-04-26 14:53:28 +09003591 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003592 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003593 Vpn vpn = mVpns.get(userId);
3594 if (vpn != null) {
3595 return vpn.prepare(oldPackage, newPackage);
3596 } else {
3597 return false;
3598 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003599 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003600 }
3601
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003602 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003603 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3604 * This method is used by system-privileged apps.
3605 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3606 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3607 *
3608 * @param packageName The package for which authorization state should change.
3609 * @param userId User for whom {@code packageName} is installed.
3610 * @param authorized {@code true} if this app should be able to start a VPN connection without
3611 * explicit user approval, {@code false} if not.
3612 *
Jeff Davidson05542602014-08-11 14:07:27 -07003613 * @hide
3614 */
3615 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003616 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3617 enforceCrossUserPermission(userId);
3618
Hugo Benichi20035e02017-04-26 14:53:28 +09003619 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003620 Vpn vpn = mVpns.get(userId);
3621 if (vpn != null) {
3622 vpn.setPackageAuthorization(packageName, authorized);
3623 }
Jeff Davidson05542602014-08-11 14:07:27 -07003624 }
3625 }
3626
3627 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003628 * Configure a TUN interface and return its file descriptor. Parameters
3629 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003630 * and not available in ConnectivityManager. Permissions are checked in
3631 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003632 * @hide
3633 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003634 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003635 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003636 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003637 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003638 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003639 return mVpns.get(user).establish(config);
3640 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003641 }
3642
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003643 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003644 * Start legacy VPN, controlling native daemons as needed. Creates a
3645 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003646 */
3647 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003648 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003649 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003650 final LinkProperties egress = getActiveLinkProperties();
3651 if (egress == null) {
3652 throw new IllegalStateException("Missing active network connection");
3653 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003654 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003655 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003656 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3657 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003658 }
3659
3660 /**
3661 * Return the information of the ongoing legacy VPN. This method is used
3662 * by VpnSettings and not available in ConnectivityManager. Permissions
3663 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003664 */
3665 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003666 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3667 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003668
Hugo Benichi20035e02017-04-26 14:53:28 +09003669 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003670 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003672 }
3673
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003674 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003675 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3676 * and not available in ConnectivityManager.
3677 */
3678 @Override
3679 public VpnInfo[] getAllVpnInfo() {
3680 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003681 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003682 if (mLockdownEnabled) {
3683 return new VpnInfo[0];
3684 }
3685
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003686 List<VpnInfo> infoList = new ArrayList<>();
3687 for (int i = 0; i < mVpns.size(); i++) {
3688 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3689 if (info != null) {
3690 infoList.add(info);
3691 }
3692 }
3693 return infoList.toArray(new VpnInfo[infoList.size()]);
3694 }
3695 }
3696
3697 /**
3698 * @return VPN information for accounting, or null if we can't retrieve all required
3699 * information, e.g primary underlying iface.
3700 */
3701 @Nullable
3702 private VpnInfo createVpnInfo(Vpn vpn) {
3703 VpnInfo info = vpn.getVpnInfo();
3704 if (info == null) {
3705 return null;
3706 }
3707 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3708 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3709 // the underlyingNetworks list.
3710 if (underlyingNetworks == null) {
3711 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3712 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3713 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3714 }
3715 } else if (underlyingNetworks.length > 0) {
3716 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3717 if (linkProperties != null) {
3718 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3719 }
3720 }
3721 return info.primaryUnderlyingIface == null ? null : info;
3722 }
3723
3724 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003725 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3726 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003727 * Permissions are checked in Vpn class.
3728 * @hide
3729 */
3730 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003731 public VpnConfig getVpnConfig(int userId) {
3732 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003733 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003734 Vpn vpn = mVpns.get(userId);
3735 if (vpn != null) {
3736 return vpn.getVpnConfig();
3737 } else {
3738 return null;
3739 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003740 }
3741 }
3742
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003743 @Override
3744 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003745 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3746 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3747 return false;
3748 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003749
Hugo Benichi69744342017-11-27 10:57:16 +09003750 synchronized (mVpns) {
3751 // Tear down existing lockdown if profile was removed
3752 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3753 if (mLockdownEnabled) {
3754 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3755 if (profileTag == null) {
3756 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3757 return false;
3758 }
3759 String profileName = new String(profileTag);
3760 final VpnProfile profile = VpnProfile.decode(
3761 profileName, mKeyStore.get(Credentials.VPN + profileName));
3762 if (profile == null) {
3763 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3764 setLockdownTracker(null);
3765 return true;
3766 }
3767 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003768 Vpn vpn = mVpns.get(user);
3769 if (vpn == null) {
3770 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3771 return false;
3772 }
3773 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003774 } else {
3775 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003776 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003777 }
3778
3779 return true;
3780 }
3781
3782 /**
3783 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3784 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3785 */
Hugo Benichi69744342017-11-27 10:57:16 +09003786 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003787 private void setLockdownTracker(LockdownVpnTracker tracker) {
3788 // Shutdown any existing tracker
3789 final LockdownVpnTracker existing = mLockdownTracker;
3790 mLockdownTracker = null;
3791 if (existing != null) {
3792 existing.shutdown();
3793 }
3794
Robin Leec3736bc2017-03-10 16:19:54 +00003795 if (tracker != null) {
3796 mLockdownTracker = tracker;
3797 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003798 }
3799 }
3800
Hugo Benichi69744342017-11-27 10:57:16 +09003801 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003802 private void throwIfLockdownEnabled() {
3803 if (mLockdownEnabled) {
3804 throw new IllegalStateException("Unavailable in lockdown mode");
3805 }
3806 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003807
Robin Lee244ce8e2016-01-05 18:03:46 +00003808 /**
Robin Lee17e61832016-05-09 13:46:28 +01003809 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3810 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003811 *
Robin Lee17e61832016-05-09 13:46:28 +01003812 * @return {@code true} if the service was started, the service was already connected, or there
3813 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003814 */
Robin Lee17e61832016-05-09 13:46:28 +01003815 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003816 synchronized (mVpns) {
3817 Vpn vpn = mVpns.get(userId);
3818 if (vpn == null) {
3819 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3820 // exists already.
3821 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3822 return false;
3823 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003824
Robin Lee812800c2016-05-13 15:38:08 +01003825 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003826 }
3827 }
3828
3829 @Override
Charles He36738632017-05-15 17:07:18 +01003830 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3831 enforceSettingsPermission();
3832 enforceCrossUserPermission(userId);
3833
3834 synchronized (mVpns) {
3835 Vpn vpn = mVpns.get(userId);
3836 if (vpn == null) {
3837 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3838 return false;
3839 }
3840 return vpn.isAlwaysOnPackageSupported(packageName);
3841 }
3842 }
3843
3844 @Override
Robin Leedc679712016-05-03 13:23:03 +01003845 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003846 enforceConnectivityInternalPermission();
3847 enforceCrossUserPermission(userId);
3848
Robin Lee244ce8e2016-01-05 18:03:46 +00003849 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003850 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3851 if (LockdownVpnTracker.isEnabled()) {
3852 return false;
3853 }
3854
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 Vpn vpn = mVpns.get(userId);
3856 if (vpn == null) {
3857 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3858 return false;
3859 }
Robin Lee17e61832016-05-09 13:46:28 +01003860 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003861 return false;
3862 }
Robin Lee17e61832016-05-09 13:46:28 +01003863 if (!startAlwaysOnVpn(userId)) {
3864 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003865 return false;
3866 }
3867 }
3868 return true;
3869 }
3870
3871 @Override
3872 public String getAlwaysOnVpnPackage(int userId) {
3873 enforceConnectivityInternalPermission();
3874 enforceCrossUserPermission(userId);
3875
3876 synchronized (mVpns) {
3877 Vpn vpn = mVpns.get(userId);
3878 if (vpn == null) {
3879 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3880 return null;
3881 }
3882 return vpn.getAlwaysOnPackage();
3883 }
3884 }
3885
Wink Savilleab9321d2013-06-29 21:10:57 -07003886 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003887 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003888 // TODO: Remove? Any reason to trigger a provisioning check?
3889 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003890 }
3891
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003892 /** Location to an updatable file listing carrier provisioning urls.
3893 * An example:
3894 *
3895 * <?xml version="1.0" encoding="utf-8"?>
3896 * <provisioningUrls>
3897 * <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 -07003898 * </provisioningUrls>
3899 */
3900 private static final String PROVISIONING_URL_PATH =
3901 "/data/misc/radio/provisioning_urls.xml";
3902 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003903
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003904 /** XML tag for root element. */
3905 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3906 /** XML tag for individual url */
3907 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003908 /** XML attribute for mcc */
3909 private static final String ATTR_MCC = "mcc";
3910 /** XML attribute for mnc */
3911 private static final String ATTR_MNC = "mnc";
3912
Paul Jensen434dde82015-06-11 09:43:30 -04003913 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003914 FileReader fileReader = null;
3915 XmlPullParser parser = null;
3916 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003917
3918 try {
3919 fileReader = new FileReader(mProvisioningUrlFile);
3920 parser = Xml.newPullParser();
3921 parser.setInput(fileReader);
3922 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3923
3924 while (true) {
3925 XmlUtils.nextElement(parser);
3926
3927 String element = parser.getName();
3928 if (element == null) break;
3929
Paul Jensen434dde82015-06-11 09:43:30 -04003930 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003931 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3932 try {
3933 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3934 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3935 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3936 parser.next();
3937 if (parser.getEventType() == XmlPullParser.TEXT) {
3938 return parser.getText();
3939 }
3940 }
3941 }
3942 } catch (NumberFormatException e) {
3943 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3944 }
3945 }
3946 }
3947 return null;
3948 } catch (FileNotFoundException e) {
3949 loge("Carrier Provisioning Urls file not found");
3950 } catch (XmlPullParserException e) {
3951 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3952 } catch (IOException e) {
3953 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3954 } finally {
3955 if (fileReader != null) {
3956 try {
3957 fileReader.close();
3958 } catch (IOException e) {}
3959 }
3960 }
3961 return null;
3962 }
3963
Wink Saville42d4f082013-07-20 20:31:59 -07003964 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003965 public String getMobileProvisioningUrl() {
3966 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003967 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003968 if (TextUtils.isEmpty(url)) {
3969 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003970 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003971 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003972 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003973 }
Wink Saville8cf35602013-07-10 23:00:07 -07003974 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003975 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003976 String phoneNumber = mTelephonyManager.getLine1Number();
3977 if (TextUtils.isEmpty(phoneNumber)) {
3978 phoneNumber = "0000000000";
3979 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003980 url = String.format(url,
3981 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3982 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003983 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003984 }
3985
Wink Savilleab9321d2013-06-29 21:10:57 -07003986 return url;
3987 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003988
Wink Saville948282b2013-08-29 08:55:16 -07003989 @Override
3990 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003991 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003992 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003993 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3994 return;
3995 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003996 final long ident = Binder.clearCallingIdentity();
3997 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003998 // Concatenate the range of types onto the range of NetIDs.
3999 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4000 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004001 } finally {
4002 Binder.restoreCallingIdentity(ident);
4003 }
Wink Saville948282b2013-08-29 08:55:16 -07004004 }
Wink Saville7788c612013-08-29 14:57:08 -07004005
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004006 @Override
4007 public void setAirplaneMode(boolean enable) {
4008 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004009 final long ident = Binder.clearCallingIdentity();
4010 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004011 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004012 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004013 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4014 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004015 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004016 } finally {
4017 Binder.restoreCallingIdentity(ident);
4018 }
4019 }
4020
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004021 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004022 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004023 Vpn userVpn = mVpns.get(userId);
4024 if (userVpn != null) {
4025 loge("Starting user already has a VPN");
4026 return;
4027 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004028 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004029 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004030 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4031 updateLockdownVpn();
4032 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004033 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004034 }
4035
4036 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004037 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004038 Vpn userVpn = mVpns.get(userId);
4039 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004040 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004041 return;
4042 }
Robin Lee17e61832016-05-09 13:46:28 +01004043 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004044 mVpns.delete(userId);
4045 }
4046 }
4047
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004048 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004049 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004050 final int vpnsSize = mVpns.size();
4051 for (int i = 0; i < vpnsSize; i++) {
4052 Vpn vpn = mVpns.valueAt(i);
4053 vpn.onUserAdded(userId);
4054 }
4055 }
4056 }
4057
4058 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004059 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004060 final int vpnsSize = mVpns.size();
4061 for (int i = 0; i < vpnsSize; i++) {
4062 Vpn vpn = mVpns.valueAt(i);
4063 vpn.onUserRemoved(userId);
4064 }
4065 }
4066 }
4067
Robin Lee89e7a692016-02-29 14:38:17 +00004068 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004069 synchronized (mVpns) {
4070 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4071 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4072 updateLockdownVpn();
4073 } else {
4074 startAlwaysOnVpn(userId);
4075 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004076 }
4077 }
4078
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004079 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4080 @Override
4081 public void onReceive(Context context, Intent intent) {
4082 final String action = intent.getAction();
4083 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4084 if (userId == UserHandle.USER_NULL) return;
4085
Robin Lee323f29d2016-05-04 16:38:06 +01004086 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004087 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004088 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004089 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004090 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4091 onUserAdded(userId);
4092 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4093 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004094 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4095 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004096 }
4097 }
4098 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004099
Robin Lee95204e02017-01-27 11:59:22 +00004100 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4101 @Override
4102 public void onReceive(Context context, Intent intent) {
4103 // Try creating lockdown tracker, since user present usually means
4104 // unlocked keystore.
4105 updateLockdownVpn();
4106 mContext.unregisterReceiver(this);
4107 }
4108 };
4109
Robert Greenwalta67be032014-05-16 15:49:14 -07004110 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4111 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004112 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4113 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004114
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004115 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4116 // Map from UID to number of NetworkRequests that UID has filed.
4117 @GuardedBy("mUidToNetworkRequestCount")
4118 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4119
Robert Greenwalta67be032014-05-16 15:49:14 -07004120 private static class NetworkFactoryInfo {
4121 public final String name;
4122 public final Messenger messenger;
4123 public final AsyncChannel asyncChannel;
4124
4125 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4126 this.name = name;
4127 this.messenger = messenger;
4128 this.asyncChannel = asyncChannel;
4129 }
4130 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004132 private void ensureNetworkRequestHasType(NetworkRequest request) {
4133 if (request.type == NetworkRequest.Type.NONE) {
4134 throw new IllegalArgumentException(
4135 "All NetworkRequests in ConnectivityService must have a type");
4136 }
4137 }
4138
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004139 /**
4140 * Tracks info about the requester.
4141 * Also used to notice when the calling process dies so we can self-expire
4142 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004145 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004146 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004147 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 final int mPid;
4149 final int mUid;
4150 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004152 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004153 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004154 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155 mPendingIntent = pi;
4156 messenger = null;
4157 mBinder = null;
4158 mPid = getCallingPid();
4159 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004160 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 }
4162
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004163 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 super();
4165 messenger = m;
4166 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004167 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 mBinder = binder;
4169 mPid = getCallingPid();
4170 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004172 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173
4174 try {
4175 mBinder.linkToDeath(this, 0);
4176 } catch (RemoteException e) {
4177 binderDied();
4178 }
4179 }
4180
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004181 private void enforceRequestCountLimit() {
4182 synchronized (mUidToNetworkRequestCount) {
4183 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4184 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004185 throw new ServiceSpecificException(
4186 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004187 }
4188 mUidToNetworkRequestCount.put(mUid, networkRequests);
4189 }
4190 }
4191
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 if (mBinder != null) {
4194 mBinder.unlinkToDeath(this, 0);
4195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196 }
4197
4198 public void binderDied() {
4199 log("ConnectivityService NetworkRequestInfo binderDied(" +
4200 request + ", " + mBinder + ")");
4201 releaseNetworkRequest(request);
4202 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004203
4204 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004205 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 }
4209
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004210 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4211 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4212 if (badCapability != null) {
4213 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004214 }
4215 }
4216
Erik Kline9d598e12015-07-13 16:37:51 +09004217 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004218 final SortedSet<Integer> thresholds = new TreeSet();
4219 synchronized (nai) {
4220 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4221 if (nri.request.networkCapabilities.hasSignalStrength() &&
4222 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4223 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4224 }
4225 }
4226 }
Erik Kline9d598e12015-07-13 16:37:51 +09004227 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004228 }
4229
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004230 private void updateSignalStrengthThresholds(
4231 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4232 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004233 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004234 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4235
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004236 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004237 String detail;
4238 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4239 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4240 } else {
4241 detail = reason;
4242 }
4243 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4244 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4245 }
4246
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004247 nai.asyncChannel.sendMessage(
4248 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004249 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004250 }
4251
Etan Cohen859748f2017-04-03 17:42:34 -07004252 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4253 if (nc == null) {
4254 return;
4255 }
4256 NetworkSpecifier ns = nc.getNetworkSpecifier();
4257 if (ns == null) {
4258 return;
4259 }
4260 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4261 ns.assertValidFromUid(Binder.getCallingUid());
4262 }
4263
Robert Greenwalt9258c642014-03-26 16:47:06 -07004264 @Override
4265 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004266 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004267 final NetworkRequest.Type type = (networkCapabilities == null)
4268 ? NetworkRequest.Type.TRACK_DEFAULT
4269 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004270 // If the requested networkCapabilities is null, take them instead from
4271 // the default network request. This allows callers to keep track of
4272 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004273 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004274 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004275 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004276 enforceAccessPermission();
4277 } else {
4278 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4279 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004280 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4281 // of the app when the request is filed, but we never change the request if the app
4282 // changes network state. http://b/29964605
4283 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004284 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004285 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004286 // Set the UID range for this request to the single UID of the requester, or to an empty
4287 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004288 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4289 // are no visible methods to set the UIDs, an app could use reflection to try and get
4290 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004291 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004292
Etan Cohenba07c8c2017-02-05 10:42:27 -08004293 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004294 throw new IllegalArgumentException("Bad timeout specified");
4295 }
Etan Cohen859748f2017-04-03 17:42:34 -07004296 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004297
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004298 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004299 nextNetworkRequestId(), type);
4300 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004301 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302
4303 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004304 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004305 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004306 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307 }
4308 return networkRequest;
4309 }
4310
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004311 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004312 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004313 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004314 } else {
4315 enforceChangePermission();
4316 }
4317 }
4318
fenglub15e72b2015-03-20 11:29:56 -07004319 @Override
fengludb571472015-04-21 17:12:05 -07004320 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004321 enforceAccessPermission();
4322 NetworkAgentInfo nai = null;
4323 if (network == null) {
4324 return false;
4325 }
4326 synchronized (mNetworkForNetId) {
4327 nai = mNetworkForNetId.get(network.netId);
4328 }
4329 if (nai != null) {
4330 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4331 return true;
4332 }
4333 return false;
4334 }
4335
Felipe Lemeee27cab2016-06-20 16:36:29 -07004336 private boolean isSystem(int uid) {
4337 return uid < Process.FIRST_APPLICATION_UID;
4338 }
fenglub15e72b2015-03-20 11:29:56 -07004339
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004340 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004341 final int uid = Binder.getCallingUid();
4342 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004343 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004344 return;
4345 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004346 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4347 // Policy already enforced.
4348 return;
4349 }
4350 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4351 // If UID is restricted, don't allow them to bring up metered APNs.
4352 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004353 }
4354 }
4355
Robert Greenwalt9258c642014-03-26 16:47:06 -07004356 @Override
4357 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4358 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004359 checkNotNull(operation, "PendingIntent cannot be null.");
4360 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4361 enforceNetworkRequestPermissions(networkCapabilities);
4362 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004363 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004364 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004365 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004366
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004367 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004368 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4369 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004370 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004371 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4372 nri));
4373 return networkRequest;
4374 }
4375
Jeremy Joslin79294842014-12-03 17:15:28 -08004376 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4377 mHandler.sendMessageDelayed(
4378 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4379 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4380 }
4381
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004382 @Override
4383 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004384 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004385 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4386 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387 }
4388
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004389 // In order to implement the compatibility measure for pre-M apps that call
4390 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4391 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4392 // This ensures it has permission to do so.
4393 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4394 if (nc == null) {
4395 return false;
4396 }
4397 int[] transportTypes = nc.getTransportTypes();
4398 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4399 return false;
4400 }
4401 try {
4402 mContext.enforceCallingOrSelfPermission(
4403 android.Manifest.permission.ACCESS_WIFI_STATE,
4404 "ConnectivityService");
4405 } catch (SecurityException e) {
4406 return false;
4407 }
4408 return true;
4409 }
4410
Robert Greenwalt9258c642014-03-26 16:47:06 -07004411 @Override
4412 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4413 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004414 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4415 enforceAccessPermission();
4416 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004417
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004418 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004419 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004420 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4421 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4422 // onLost and onAvailable callbacks when networks move in and out of the background.
4423 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4424 // can't request networks.
4425 restrictBackgroundRequestForCaller(nc);
4426 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004427
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004428 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004429 NetworkRequest.Type.LISTEN);
4430 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004431 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004432
4433 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4434 return networkRequest;
4435 }
4436
4437 @Override
4438 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4439 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004440 checkNotNull(operation, "PendingIntent cannot be null.");
4441 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4442 enforceAccessPermission();
4443 }
Etan Cohen859748f2017-04-03 17:42:34 -07004444 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004445
Chalard Jeandda156a2018-01-10 21:19:32 +09004446 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004447 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004448
4449 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004450 NetworkRequest.Type.LISTEN);
4451 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004452 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004453
4454 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004455 }
4456
Erik Klineacdd6392016-07-07 16:50:58 +09004457 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004458 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004459 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004460 mHandler.sendMessage(mHandler.obtainMessage(
4461 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004462 }
4463
4464 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004465 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004466 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004467 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4468 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004469 }
4470
Robert Greenwalta67be032014-05-16 15:49:14 -07004471 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004472 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004473 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4474 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4475 }
4476
4477 @Override
4478 public void unregisterNetworkFactory(Messenger messenger) {
4479 enforceConnectivityInternalPermission();
4480 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4481 }
4482
4483 private void handleUnregisterNetworkFactory(Messenger messenger) {
4484 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4485 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004486 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004487 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004488 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004489 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004490 }
4491
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 /**
4493 * NetworkAgentInfo supporting a request by requestId.
4494 * These have already been vetted (their Capabilities satisfy the request)
4495 * and the are the highest scored network available.
4496 * the are keyed off the Requests requestId.
4497 */
Hugo Benichicd952782017-09-20 11:20:14 +09004498 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4499 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4501 new SparseArray<NetworkAgentInfo>();
4502
Paul Jensen31a94f42015-02-13 14:18:39 -05004503 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4504 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004505 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4506 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004507 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4508 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4509 // there may not be a strict 1:1 correlation between the two.
4510 @GuardedBy("mNetworkForNetId")
4511 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512
Robert Greenwalt7b816022014-04-18 15:25:25 -07004513 // NetworkAgentInfo keyed off its connecting messenger
4514 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004515 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4517 new HashMap<Messenger, NetworkAgentInfo>();
4518
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004519 @GuardedBy("mBlockedAppUids")
4520 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4521
Paul Jensen2c311d62014-11-17 12:34:51 -05004522 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 private final NetworkRequest mDefaultRequest;
4524
Erik Klineda4bfa82015-04-30 12:58:40 +09004525 // Request used to optionally keep mobile data active even when higher
4526 // priority networks like Wi-Fi are active.
4527 private final NetworkRequest mDefaultMobileDataRequest;
4528
Hugo Benichicd952782017-09-20 11:20:14 +09004529 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4530 synchronized (mNetworkForRequestId) {
4531 return mNetworkForRequestId.get(requestId);
4532 }
4533 }
4534
4535 private void clearNetworkForRequest(int requestId) {
4536 synchronized (mNetworkForRequestId) {
4537 mNetworkForRequestId.remove(requestId);
4538 }
4539 }
4540
4541 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4542 synchronized (mNetworkForRequestId) {
4543 mNetworkForRequestId.put(requestId, nai);
4544 }
4545 }
4546
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004547 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004548 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004549 }
4550
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004551 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004552 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004553 }
4554
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004555 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4556 return nri.request.requestId == mDefaultRequest.requestId;
4557 }
4558
Paul Jensen31a94f42015-02-13 14:18:39 -05004559 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004561 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562 enforceConnectivityInternalPermission();
4563
Rubin Xu1bb5c082017-09-05 18:40:49 +01004564 LinkProperties lp = new LinkProperties(linkProperties);
4565 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004566 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4567 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004568 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004569 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004570 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004571 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004572 // Make sure the network capabilities reflect what the agent info says.
4573 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004574 synchronized (this) {
4575 nai.networkMonitor.systemReady = mSystemReady;
4576 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004577 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4578 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004579 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004581 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
4583
4584 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4585 if (VDBG) log("Got NetworkAgent Messenger");
4586 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004587 synchronized (mNetworkForNetId) {
4588 mNetworkForNetId.put(na.network.netId, na);
4589 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004590 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4591 NetworkInfo networkInfo = na.networkInfo;
4592 na.networkInfo = null;
4593 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004594 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004595 }
4596
4597 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4598 LinkProperties newLp = networkAgent.linkProperties;
4599 int netId = networkAgent.network.netId;
4600
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004601 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4602 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004603 if (networkAgent.clatd != null) {
4604 networkAgent.clatd.fixupLinkProperties(oldLp);
4605 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004606
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004607 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 updateMtu(newLp, oldLp);
4609 // TODO - figure out what to do for clat
4610// for (LinkProperties lp : newLp.getStackedLinks()) {
4611// updateMtu(lp, null);
4612// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004613 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004614
Erik Kline94887872016-04-05 13:30:49 +09004615 updateRoutes(newLp, oldLp, netId);
4616 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004617
Hugo Benichi6f62b732017-06-27 15:13:20 +09004618 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004619 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004620 if (isDefaultNetwork(networkAgent)) {
4621 handleApplyDefaultProxy(newLp.getHttpProxy());
4622 } else {
4623 updateProxy(newLp, oldLp, networkAgent);
4624 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004625 // TODO - move this check to cover the whole function
4626 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004627 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004628 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4629 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004630
4631 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004632 }
4633
Joel Scherpelz668370b2017-06-08 15:35:21 +09004634 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004635 // Marks are only available on WiFi interaces. Checking for
4636 // marks on unsupported interfaces is harmless.
4637 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4638 return;
4639 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004640
Joel Scherpelz668370b2017-06-08 15:35:21 +09004641 int mark = mContext.getResources().getInteger(
4642 com.android.internal.R.integer.config_networkWakeupPacketMark);
4643 int mask = mContext.getResources().getInteger(
4644 com.android.internal.R.integer.config_networkWakeupPacketMask);
4645
4646 // Mask/mark of zero will not detect anything interesting.
4647 // Don't install rules unless both values are nonzero.
4648 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004649 return;
4650 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004651
4652 final String prefix = "iface:" + iface;
4653 try {
4654 if (add) {
4655 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4656 } else {
4657 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4658 }
4659 } catch (Exception e) {
4660 loge("Exception modifying wakeup packet monitoring: " + e);
4661 }
4662
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004663 }
4664
4665 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4666 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004667 CompareResult<String> interfaceDiff = new CompareResult<String>(
4668 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4669 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004670 for (String iface : interfaceDiff.added) {
4671 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004672 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004673 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004674 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004675 } catch (Exception e) {
4676 loge("Exception adding interface: " + e);
4677 }
4678 }
4679 for (String iface : interfaceDiff.removed) {
4680 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004681 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004682 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004683 mNetd.removeInterfaceFromNetwork(iface, netId);
4684 } catch (Exception e) {
4685 loge("Exception removing interface: " + e);
4686 }
4687 }
4688 }
4689
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004690 /**
4691 * Have netd update routes from oldLp to newLp.
4692 * @return true if routes changed between oldLp and newLp
4693 */
4694 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004695 // Compare the route diff to determine which routes should be added and removed.
4696 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4697 oldLp != null ? oldLp.getAllRoutes() : null,
4698 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699
4700 // add routes before removing old in case it helps with continuous connectivity
4701
4702 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4703 for (RouteInfo route : routeDiff.added) {
4704 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004705 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004706 try {
4707 mNetd.addRoute(netId, route);
4708 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004709 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4710 loge("Exception in addRoute for non-gateway: " + e);
4711 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004712 }
4713 }
4714 for (RouteInfo route : routeDiff.added) {
4715 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004716 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717 try {
4718 mNetd.addRoute(netId, route);
4719 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004720 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4721 loge("Exception in addRoute for gateway: " + e);
4722 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004723 }
4724 }
4725
4726 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004727 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004728 try {
4729 mNetd.removeRoute(netId, route);
4730 } catch (Exception e) {
4731 loge("Exception in removeRoute: " + e);
4732 }
4733 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004734 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004735 }
Erik Kline41368502015-06-17 13:19:54 +09004736
Erik Kline94887872016-04-05 13:30:49 +09004737 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4738 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4739 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004740 }
Erik Kline94887872016-04-05 13:30:49 +09004741
Erik Kline1742fe12017-12-13 19:40:49 +09004742 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4743 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4744
Erik Klinea24d4592018-01-11 21:07:29 +09004745 if (DBG) {
4746 final Collection<InetAddress> dnses = newLp.getDnsServers();
4747 log("Setting DNS servers for network " + netId + " to " + dnses);
4748 }
Erik Kline94887872016-04-05 13:30:49 +09004749 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004750 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004751 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004752 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004753 }
Erik Kline4edba012017-04-07 15:29:29 +09004754 }
4755
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004756 private String getNetworkPermission(NetworkCapabilities nc) {
4757 // TODO: make these permission strings AIDL constants instead.
4758 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4759 return NetworkManagementService.PERMISSION_SYSTEM;
4760 }
4761 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4762 return NetworkManagementService.PERMISSION_NETWORK;
4763 }
4764 return null;
4765 }
4766
Paul Jensen3d194ea2015-06-16 14:27:36 -04004767 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004768 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4769 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4770 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004771 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004772 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004773 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004774 if (nai.everConnected &&
4775 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4776 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004777 // does not cause any request (that is not a listen) currently matching that agent to
4778 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004779 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004780 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004781 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004782 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004783 }
4784
Paul Jensen3d194ea2015-06-16 14:27:36 -04004785 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004786 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004787 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004788 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004789 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004790 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004791 }
Paul Jensene0988542015-06-25 15:30:08 -04004792 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004793 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004794 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004795 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004796 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004797 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004798 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004799 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004800 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004801 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004802 if (nai.isSuspended()) {
4803 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4804 } else {
4805 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4806 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004807
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004808 return newNc;
4809 }
4810
4811 /**
4812 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4813 *
4814 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4815 * capabilities we manage and store in {@code nai}, such as validated status and captive
4816 * portal status)
4817 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4818 * potentially triggers rematches.
4819 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4820 * change.)
4821 *
4822 * @param oldScore score of the network before any of the changes that prompted us
4823 * to call this function.
4824 * @param nai the network having its capabilities updated.
4825 * @param nc the new network capabilities.
4826 */
4827 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4828 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4829
4830 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004831
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004832 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004834 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004835 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004836 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004837 } catch (RemoteException e) {
4838 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004839 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004840 }
4841
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004842 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004843 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004844 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004845 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004846 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004847
Chalard Jeanf213ca12018-01-16 18:43:05 +09004848 updateUids(nai, prevNc, newNc);
4849
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004850 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004851 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4852 // the change we're processing can't affect any requests, it can only affect the listens
4853 // on this network. We might have been called by rematchNetworkAndRequests when a
4854 // network changed foreground state.
4855 processListenRequests(nai, true);
4856 } else {
4857 // If the requestable capabilities have changed or the score changed, we can't have been
4858 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004859 rematchAllNetworksAndRequests(nai, oldScore);
4860 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004861 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004862
4863 // Report changes that are interesting for network statistics tracking.
4864 if (prevNc != null) {
4865 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004866 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004867 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004868 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004869 if (meteredChanged || roamingChanged) {
4870 notifyIfacesChangedForNetworkStats();
4871 }
4872 }
4873
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004874 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004875 // Tell VPNs about updated capabilities, since they may need to
4876 // bubble those changes through.
4877 synchronized (mVpns) {
4878 for (int i = 0; i < mVpns.size(); i++) {
4879 final Vpn vpn = mVpns.valueAt(i);
4880 vpn.updateCapabilities();
4881 }
4882 }
4883 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004884 }
4885
Chalard Jeanf213ca12018-01-16 18:43:05 +09004886 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4887 NetworkCapabilities newNc) {
4888 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4889 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4890 if (null == prevRanges) prevRanges = new ArraySet<>();
4891 if (null == newRanges) newRanges = new ArraySet<>();
4892 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4893
4894 prevRanges.removeAll(newRanges);
4895 newRanges.removeAll(prevRangesCopy);
4896
4897 try {
4898 if (!newRanges.isEmpty()) {
4899 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4900 newRanges.toArray(addedRangesArray);
4901 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4902 }
4903 if (!prevRanges.isEmpty()) {
4904 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4905 prevRanges.toArray(removedRangesArray);
4906 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4907 }
4908 } catch (Exception e) {
4909 // Never crash!
4910 loge("Exception in updateUids: " + e);
4911 }
4912 }
4913
Hugo Benichief502882017-09-01 01:23:32 +00004914 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4915 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4916 // Ignore updates for disconnected networks
4917 return;
4918 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004919 // newLp is already a defensive copy.
4920 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004921 if (VDBG) {
4922 log("Update of LinkProperties for " + nai.name() +
4923 "; created=" + nai.created +
4924 "; everConnected=" + nai.everConnected);
4925 }
4926 LinkProperties oldLp = nai.linkProperties;
4927 synchronized (nai) {
4928 nai.linkProperties = newLp;
4929 }
4930 if (nai.everConnected) {
4931 updateLinkProperties(nai, oldLp);
4932 }
4933 }
4934
Paul Jensenc8b9a742014-09-30 15:37:41 -04004935 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004936 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4937 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004938 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004939 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004940 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4941 }
4942 }
4943
Robert Greenwalt7b816022014-04-18 15:25:25 -07004944 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4945 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004946 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004947 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4948 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004949 }
4950 }
4951
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004952 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4953 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004954 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004955 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004956 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4957 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004958 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004959 sendIntent(nri.mPendingIntent, intent);
4960 }
4961 // else not handled
4962 }
4963
4964 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4965 mPendingIntentWakeLock.acquire();
4966 try {
4967 if (DBG) log("Sending " + pendingIntent);
4968 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4969 } catch (PendingIntent.CanceledException e) {
4970 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4971 mPendingIntentWakeLock.release();
4972 releasePendingNetworkRequest(pendingIntent);
4973 }
4974 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4975 }
4976
4977 @Override
4978 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4979 String resultData, Bundle resultExtras) {
4980 if (DBG) log("Finished sending " + pendingIntent);
4981 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004982 // Release with a delay so the receiving client has an opportunity to put in its
4983 // own request.
4984 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004985 }
4986
Chalard Jeanf19db372018-01-26 19:24:40 +09004987 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004988 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004989 if (nri.messenger == null) {
4990 return; // Default request has no msgr
4991 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004992 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004993 // TODO: check if defensive copies of data is needed.
4994 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004995 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004996 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4997 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004998 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004999 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005000 case ConnectivityManager.CALLBACK_AVAILABLE: {
5001 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5002 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5003 break;
5004 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005005 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005006 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005007 break;
5008 }
5009 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005010 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09005011 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
5012 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005013 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005014 break;
5015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005016 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005017 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005018 break;
5019 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005020 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005021 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005022 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005023 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005024 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005025 String notification = ConnectivityManager.getCallbackName(notificationType);
5026 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005027 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005028 nri.messenger.send(msg);
5029 } catch (RemoteException e) {
5030 // may occur naturally in the race of binder death.
5031 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5032 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005033 }
5034
Hugo Benichidba33db2017-03-23 22:40:44 +09005035 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5036 bundle.putParcelable(t.getClass().getSimpleName(), t);
5037 }
5038
Paul Jensenc8b9a742014-09-30 15:37:41 -04005039 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005040 if (nai.numRequestNetworkRequests() != 0) {
5041 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5042 NetworkRequest nr = nai.requestAt(i);
5043 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005044 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005045 loge("Dead network still had at least " + nr);
5046 break;
5047 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005048 }
5049 nai.asyncChannel.disconnect();
5050 }
5051
Robert Greenwalt7b816022014-04-18 15:25:25 -07005052 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5053 if (oldNetwork == null) {
5054 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5055 return;
5056 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005057 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005058
5059 // If we get here it means that the last linger timeout for this network expired. So there
5060 // must be no other active linger timers, and we must stop lingering.
5061 oldNetwork.clearLingerState();
5062
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005063 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005064 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005065 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005066 } else {
5067 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005068 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5069 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005070 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071 }
5072
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005073 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005074 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005075 setupDataActivityTracking(newNetwork);
5076 try {
5077 mNetd.setDefaultNetId(newNetwork.network.netId);
5078 } catch (Exception e) {
5079 loge("Exception setting default network :" + e);
5080 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005081
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005082 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005083 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005084 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005085 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005086 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005087 }
5088
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005089 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005090 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5091 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5092 NetworkRequest nr = nri.request;
5093 if (!nr.isListen()) continue;
5094 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5095 nai.removeRequest(nri.request.requestId);
5096 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5097 }
5098 }
5099
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005100 if (capabilitiesChanged) {
5101 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5102 }
5103
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005104 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5105 NetworkRequest nr = nri.request;
5106 if (!nr.isListen()) continue;
5107 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5108 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005109 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005110 }
5111 }
5112 }
5113
Paul Jensen2161a8e2014-09-11 11:00:39 -04005114 // Handles a network appearing or improving its score.
5115 //
5116 // - Evaluates all current NetworkRequests that can be
5117 // satisfied by newNetwork, and reassigns to newNetwork
5118 // any such requests for which newNetwork is the best.
5119 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005120 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005121 // needed. A network is needed if it is the best network for
5122 // one or more NetworkRequests, or if it is a VPN.
5123 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005124 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005125 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005126 //
5127 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5128 // networks that have no chance (i.e. even if validated)
5129 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005130 //
5131 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5132 // it does not remove NetworkRequests that other Networks could better satisfy.
5133 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5134 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5135 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005136 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005137 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005138 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5139 // performed to tear down unvalidated networks that have no chance (i.e. even if
5140 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005141 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005142 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005143 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005144 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005145 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005146 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005147
5148 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5149 final int score = newNetwork.getCurrentScore();
5150
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005151 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005152
Paul Jensen2161a8e2014-09-11 11:00:39 -04005153 // Find and migrate to this Network any NetworkRequests for
5154 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005155 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005156 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005157 NetworkCapabilities nc = newNetwork.networkCapabilities;
5158 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005159 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005160 // Process requests in the first pass and listens in the second pass. This allows us to
5161 // change a network's capabilities depending on which requests it has. This is only
5162 // correct if the change in capabilities doesn't affect whether the network satisfies
5163 // requests or not, and doesn't affect the network's score.
5164 if (nri.request.isListen()) continue;
5165
Hugo Benichicd952782017-09-20 11:20:14 +09005166 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005167 final boolean satisfies = newNetwork.satisfies(nri.request);
5168 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005169 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005170 log("Network " + newNetwork.name() + " was already satisfying" +
5171 " request " + nri.request.requestId + ". No change.");
5172 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005173 keep = true;
5174 continue;
5175 }
5176
5177 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005178 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005179 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005180 // next check if it's better than any current network we're using for
5181 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005182 if (VDBG) {
5183 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005184 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005185 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005186 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005187 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005188 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005189 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005190 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005191 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005192 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005193 affectedNetworks.add(currentNetwork);
5194 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005195 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005196 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005197 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005198 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005199 if (!newNetwork.addRequest(nri.request)) {
5200 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5201 }
5202 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005203 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005204 // Tell NetworkFactories about the new score, so they can stop
5205 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005206 // TODO - this could get expensive if we have alot of requests for this
5207 // network. Think about if there is a way to reduce this. Push
5208 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005209 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005210 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005211 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005212 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005213 if (currentNetwork != null) {
5214 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005216 }
5217 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005218 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005219 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5220 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005221 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005222 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5223 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5224 // This means this code doesn't have to handle the case where "currentNetwork" no
5225 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5226 if (DBG) {
5227 log("Network " + newNetwork.name() + " stopped satisfying" +
5228 " request " + nri.request.requestId);
5229 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005230 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005231 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005232 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005233 sendUpdatedScoreToFactories(nri.request, 0);
5234 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005235 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5236 newNetwork.name() +
5237 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005238 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005239 // TODO: Technically, sending CALLBACK_LOST here is
5240 // incorrect if there is a replacement network currently
5241 // connected that can satisfy nri, which is a request
5242 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005243 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5244 // so this code is only incorrect for a network that loses
5245 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005246 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005247 }
5248 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005249 if (isNewDefault) {
5250 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005251 makeDefault(newNetwork);
5252 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005253 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005254 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005255 // Have a new default network, release the transition wakelock in
5256 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005257 }
5258
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005259 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5260 Slog.wtf(TAG, String.format(
5261 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005262 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005263 }
5264 if (newNetwork.getCurrentScore() != score) {
5265 Slog.wtf(TAG, String.format(
5266 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005267 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005268 }
5269
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005270 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005271 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5272 // If the network went from background to foreground or vice versa, we need to update
5273 // its foreground state. It is safe to do this after rematching the requests because
5274 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5275 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005276 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005277 } else {
5278 processListenRequests(newNetwork, false);
5279 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005280
Paul Jensencf4c2c62015-07-01 14:16:32 -04005281 // do this after the default net is switched, but
5282 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005283 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005285 // Linger any networks that are no longer needed. This should be done after sending the
5286 // available callback for newNetwork.
5287 for (NetworkAgentInfo nai : affectedNetworks) {
5288 updateLingerState(nai, now);
5289 }
5290 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5291 // does not need to be done in any particular order.
5292 updateLingerState(newNetwork, now);
5293
Paul Jensencf4c2c62015-07-01 14:16:32 -04005294 if (isNewDefault) {
5295 // Maintain the illusion: since the legacy API only
5296 // understands one network at a time, we must pretend
5297 // that the current default network disconnected before
5298 // the new one connected.
5299 if (oldDefaultNetwork != null) {
5300 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5301 oldDefaultNetwork, true);
5302 }
5303 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5304 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5305 notifyLockdownVpn(newNetwork);
5306 }
5307
Robert Greenwalt7b816022014-04-18 15:25:25 -07005308 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005309 // Notify battery stats service about this network, both the normal
5310 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005311 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005312 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005313 final IBatteryStats bs = BatteryStatsService.getService();
5314 final int type = newNetwork.networkInfo.getType();
5315
5316 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5317 bs.noteNetworkInterfaceType(baseIface, type);
5318 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5319 final String stackedIface = stacked.getInterfaceName();
5320 bs.noteNetworkInterfaceType(stackedIface, type);
5321 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5322 }
5323 } catch (RemoteException ignored) {
5324 }
5325
Robert Greenwalt152ed372014-12-17 17:19:53 -08005326 // This has to happen after the notifyNetworkCallbacks as that tickles each
5327 // ConnectivityManager instance so that legacy requests correctly bind dns
5328 // requests to this network. The legacy users are listening for this bcast
5329 // and will generally do a dns request so they can ensureRouteToHost and if
5330 // they do that before the callbacks happen they'll use the default network.
5331 //
5332 // TODO: Is there still a race here? We send the broadcast
5333 // after sending the callback, but if the app can receive the
5334 // broadcast before the callback, it might still break.
5335 //
5336 // This *does* introduce a race where if the user uses the new api
5337 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5338 // they may get old info. Reverse this after the old startUsing api is removed.
5339 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005340 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5341 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005342 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005343 // legacy type tracker filters out repeat adds
5344 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5345 }
5346 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005347
5348 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5349 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5350 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5351 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5352 if (newNetwork.isVPN()) {
5353 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005355 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005356 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5357 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005358 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005359 if (nai.getLingerExpiry() > 0) {
5360 // This network has active linger timers and no requests, but is not
5361 // lingering. Linger it.
5362 //
5363 // One way (the only way?) this can happen if this network is unvalidated
5364 // and became unneeded due to another network improving its score to the
5365 // point where this network will no longer be able to satisfy any requests
5366 // even if it validates.
5367 updateLingerState(nai, now);
5368 } else {
5369 if (DBG) log("Reaping " + nai.name());
5370 teardownUnneededNetwork(nai);
5371 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005372 }
5373 }
5374 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005375 }
5376
Paul Jensen1c7ba022015-06-16 14:27:36 -04005377 /**
5378 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5379 * being disconnected.
5380 * @param changed If only one Network's score or capabilities have been modified since the last
5381 * time this function was called, pass this Network in this argument, otherwise pass
5382 * null.
5383 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5384 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5385 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5386 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5387 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005388 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005389 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005390 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5391 // to avoid the slowness. It is not simply enough to process just "changed", for
5392 // example in the case where "changed"'s score decreases and another network should begin
5393 // satifying a NetworkRequest that "changed" currently satisfies.
5394
5395 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5396 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5397 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005398 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005399 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005400 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005401 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005402 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5403 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5404 // Rematch higher scoring networks first to prevent requests first matching a lower
5405 // scoring network and then a higher scoring network, which could produce multiple
5406 // callbacks and inadvertently unlinger networks.
5407 Arrays.sort(nais);
5408 for (NetworkAgentInfo nai : nais) {
5409 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005410 // Only reap the last time through the loop. Reaping before all rematching
5411 // is complete could incorrectly teardown a network that hasn't yet been
5412 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005413 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005414 : ReapUnvalidatedNetworks.REAP,
5415 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005416 }
5417 }
5418 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005419
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005420 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005421 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005422 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005423 // For now only update icons for default connection.
5424 // TODO: Update WiFi and cellular icons separately. b/17237507
5425 if (!isDefaultNetwork(nai)) return;
5426
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005427 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005428 // Don't repeat publish.
5429 if (newInetCondition == mDefaultInetConditionPublished) return;
5430
5431 mDefaultInetConditionPublished = newInetCondition;
5432 sendInetConditionBroadcast(nai.networkInfo);
5433 }
5434
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005435 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005436 synchronized (mVpns) {
5437 if (mLockdownTracker != null) {
5438 if (nai != null && nai.isVPN()) {
5439 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5440 } else {
5441 mLockdownTracker.onNetworkInfoChanged();
5442 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005443 }
5444 }
5445 }
5446
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005448 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005449 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005450 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005451 synchronized (networkAgent) {
5452 oldInfo = networkAgent.networkInfo;
5453 networkAgent.networkInfo = newInfo;
5454 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005455 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005456
Robert Greenwalt7b816022014-04-18 15:25:25 -07005457 if (DBG) {
5458 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5459 (oldInfo == null ? "null" : oldInfo.getState()) +
5460 " to " + state);
5461 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005462
Robin Lee585e2482016-05-01 23:00:00 +01005463 if (!networkAgent.created
5464 && (state == NetworkInfo.State.CONNECTED
5465 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005466
5467 // A network that has just connected has zero requests and is thus a foreground network.
5468 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5469
Robert Greenwalt7b816022014-04-18 15:25:25 -07005470 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005471 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005472 if (networkAgent.isVPN()) {
5473 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005474 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5475 (networkAgent.networkMisc == null ||
5476 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005477 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005478 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005479 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005480 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005481 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005482 loge("Error creating network " + networkAgent.network.netId + ": "
5483 + e.getMessage());
5484 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005485 }
Paul Jenseneec75412014-08-04 12:21:19 -04005486 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005487 }
5488
5489 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5490 networkAgent.everConnected = true;
5491
Robert Greenwalt7b816022014-04-18 15:25:25 -07005492 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005493 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005494
Paul Jensenca8f16a2014-05-09 12:47:55 -04005495 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005496 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005497
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005498 if (networkAgent.isVPN()) {
5499 // Temporarily disable the default proxy (not global).
5500 synchronized (mProxyLock) {
5501 if (!mDefaultProxyDisabled) {
5502 mDefaultProxyDisabled = true;
5503 if (mGlobalProxy == null && mDefaultProxy != null) {
5504 sendProxyBroadcast(null);
5505 }
5506 }
5507 }
5508 // TODO: support proxy per network.
5509 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005510
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005511 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5512 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5513 // capabilities, so it only needs to be done once on initial connect, not every time the
5514 // network's capabilities change. Note that we do this before rematching the network,
5515 // so we could decide to tear it down immediately afterwards. That's fine though - on
5516 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5517 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005518 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005519
Paul Jensen2161a8e2014-09-11 11:00:39 -04005520 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005521 final long now = SystemClock.elapsedRealtime();
5522 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005523
5524 // This has to happen after matching the requests, because callbacks are just requests.
5525 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005526 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005527 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005528 if (networkAgent.isVPN()) {
5529 synchronized (mProxyLock) {
5530 if (mDefaultProxyDisabled) {
5531 mDefaultProxyDisabled = false;
5532 if (mGlobalProxy == null && mDefaultProxy != null) {
5533 sendProxyBroadcast(mDefaultProxy);
5534 }
5535 }
5536 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005537 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005538 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005539 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5540 state == NetworkInfo.State.SUSPENDED) {
5541 // going into or coming out of SUSPEND: rescore and notify
5542 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005543 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005544 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005545 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5546 networkAgent.networkCapabilities);
5547 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5548 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005549 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5550 ConnectivityManager.CALLBACK_SUSPENDED :
5551 ConnectivityManager.CALLBACK_RESUMED));
5552 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005553 }
5554 }
5555
Robert Greenwaltac96c522014-06-03 16:43:57 -07005556 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005557 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005558 if (score < 0) {
5559 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5560 "). Bumping score to min of 0");
5561 score = 0;
5562 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005563
Paul Jensen2161a8e2014-09-11 11:00:39 -04005564 final int oldScore = nai.getCurrentScore();
5565 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005566
Paul Jensen85cf78e2015-06-25 13:25:07 -04005567 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005568
Paul Jensenc8b9a742014-09-30 15:37:41 -04005569 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005570 }
5571
Erik Klinec75d4fa2017-02-15 19:59:17 +09005572 // Notify only this one new request of the current state. Transfer all the
5573 // current state by calling NetworkCapabilities and LinkProperties callbacks
5574 // so that callers can be guaranteed to have as close to atomicity in state
5575 // transfer as can be supported by this current API.
5576 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005577 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005578 if (nri.mPendingIntent != null) {
5579 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5580 // Attempt no subsequent state pushes where intents are involved.
5581 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005582 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005583
5584 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005585 }
5586
Robert Greenwalt8d482522015-06-24 13:23:42 -07005587 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005588 // The NetworkInfo we actually send out has no bearing on the real
5589 // state of affairs. For example, if the default connection is mobile,
5590 // and a request for HIPRI has just gone away, we need to pretend that
5591 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5592 // the state to DISCONNECTED, even though the network is of type MOBILE
5593 // and is still connected.
5594 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5595 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005596 if (state != DetailedState.DISCONNECTED) {
5597 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005598 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005599 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005600 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005601 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5602 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5603 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5604 if (info.isFailover()) {
5605 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5606 nai.networkInfo.setFailover(false);
5607 }
5608 if (info.getReason() != null) {
5609 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5610 }
5611 if (info.getExtraInfo() != null) {
5612 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5613 }
5614 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005615 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005616 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005617 if (newDefaultAgent != null) {
5618 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5619 newDefaultAgent.networkInfo);
5620 } else {
5621 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5622 }
5623 }
5624 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5625 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005626 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005627 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005628 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005629 }
5630 }
5631 }
5632
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005633 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005634 if (VDBG) {
5635 String notification = ConnectivityManager.getCallbackName(notifyType);
5636 log("notifyType " + notification + " for " + networkAgent.name());
5637 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005638 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5639 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005640 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5641 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005642 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5643 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005644 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005645 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005646 } else {
5647 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5648 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005649 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005650 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005651
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005652 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5653 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5654 }
5655
Jeff Sharkey69736342014-12-08 14:50:12 -08005656 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005657 * Returns the list of all interfaces that could be used by network traffic that does not
5658 * explicitly specify a network. This includes the default network, but also all VPNs that are
5659 * currently connected.
5660 *
5661 * Must be called on the handler thread.
5662 */
5663 private Network[] getDefaultNetworks() {
5664 ArrayList<Network> defaultNetworks = new ArrayList<>();
5665 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5666 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5667 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5668 defaultNetworks.add(nai.network);
5669 }
5670 }
5671 return defaultNetworks.toArray(new Network[0]);
5672 }
5673
5674 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005675 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5676 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005677 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005678 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005679 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005680 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005681 } catch (Exception ignored) {
5682 }
5683 }
5684
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005685 @Override
5686 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005687 int user = UserHandle.getUserId(Binder.getCallingUid());
5688 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005689 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005690 return mVpns.get(user).addAddress(address, prefixLength);
5691 }
5692 }
5693
5694 @Override
5695 public boolean removeVpnAddress(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).removeAddress(address, prefixLength);
5700 }
5701 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005702
5703 @Override
5704 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005705 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005706 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005707 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005708 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005709 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005710 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005711 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005712 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005713 }
5714 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005715 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005716
5717 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005718 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005719 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005720 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005721 }
5722
5723 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005724 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5725 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5726 enforceKeepalivePermission();
5727 mKeepaliveTracker.startNattKeepalive(
5728 getNetworkAgentInfoForNetwork(network),
5729 intervalSeconds, messenger, binder,
5730 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5731 }
5732
5733 @Override
5734 public void stopKeepalive(Network network, int slot) {
5735 mHandler.sendMessage(mHandler.obtainMessage(
5736 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5737 }
5738
5739 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005740 public void factoryReset() {
5741 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005742
5743 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5744 return;
5745 }
5746
Robin Lee3b3dd942015-05-12 18:14:58 +01005747 final int userId = UserHandle.getCallingUserId();
5748
Stuart Scottf1fb3972015-04-02 18:00:02 -07005749 // Turn airplane mode off
5750 setAirplaneMode(false);
5751
Stuart Scotte3e314d2015-04-20 14:07:45 -07005752 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5753 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005754 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005755 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005756 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005757 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005758 }
5759
Stuart Scotte3e314d2015-04-20 14:07:45 -07005760 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005761 // Remove always-on package
5762 synchronized (mVpns) {
5763 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5764 if (alwaysOnPackage != null) {
5765 setAlwaysOnVpnPackage(userId, null, false);
5766 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5767 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005768
Hugo Benichi69744342017-11-27 10:57:16 +09005769 // Turn Always-on VPN off
5770 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5771 final long ident = Binder.clearCallingIdentity();
5772 try {
5773 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5774 mLockdownEnabled = false;
5775 setLockdownTracker(null);
5776 } finally {
5777 Binder.restoreCallingIdentity(ident);
5778 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005779 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005780
Hugo Benichi69744342017-11-27 10:57:16 +09005781 // Turn VPN off
5782 VpnConfig vpnConfig = getVpnConfig(userId);
5783 if (vpnConfig != null) {
5784 if (vpnConfig.legacy) {
5785 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5786 } else {
5787 // Prevent this app (packagename = vpnConfig.user) from initiating
5788 // VPN connections in the future without user intervention.
5789 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005790
Hugo Benichi69744342017-11-27 10:57:16 +09005791 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5792 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005793 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005794 }
5795 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005796
5797 Settings.Global.putString(mContext.getContentResolver(),
5798 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005799 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005800
Ricky Wai44dcbde2018-01-23 04:09:45 +00005801 @Override
5802 public byte[] getNetworkWatchlistConfigHash() {
5803 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5804 if (nwm == null) {
5805 loge("Unable to get NetworkWatchlistManager");
5806 return null;
5807 }
5808 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5809 return nwm.getWatchlistConfigHash();
5810 }
5811
Paul Jensencf4c2c62015-07-01 14:16:32 -04005812 @VisibleForTesting
5813 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5814 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5815 return new NetworkMonitor(context, handler, nai, defaultRequest);
5816 }
Erik Kline48f12f22016-04-14 17:30:59 +09005817
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005818 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005819 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5820 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005821 }
5822
5823 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005824 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5825 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5826 }
5827
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005828 @VisibleForTesting
5829 public boolean hasService(String name) {
5830 return ServiceManager.checkService(name) != null;
5831 }
5832
Hugo Benichi64901e52017-10-19 14:42:40 +09005833 @VisibleForTesting
5834 protected IpConnectivityMetrics.Logger metricsLogger() {
5835 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5836 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005837 }
5838
5839 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005840 int[] transports = nai.networkCapabilities.getTransportTypes();
5841 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005842 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005843
5844 private static boolean toBool(int encodedBoolean) {
5845 return encodedBoolean != 0; // Only 0 means false.
5846 }
5847
5848 private static int encodeBool(boolean b) {
5849 return b ? 1 : 0;
5850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851}