blob: 10f82934d7c337d7316b0b6783d67645a379e893 [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;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090022import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040027import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060032import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060034import static android.net.NetworkCapabilities.TRANSPORT_VPN;
35
Hugo Benichia0385682017-03-22 17:07:57 +090036import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037
Wenchao Tongf5ea3402015-03-04 13:26:38 -080038import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080039import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090040import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070041import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090058import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090066import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070068import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070069import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070070import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070071import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070072import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040073import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070074import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040075import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040076import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060077import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090078import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090079import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090080import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080082import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070083import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090093import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090098import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090099import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900100import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700101import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400102import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700104import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700105import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700107import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600127import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700128import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900129import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900130import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700131import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400133import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900134import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900135import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900136import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900137import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100138import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700139import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700140import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600141import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400142import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900143import com.android.server.connectivity.NetworkNotificationManager;
144import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400145import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700146import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800147import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700148import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900149import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700150import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700151import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900152import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600153
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700154import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700155
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700156import org.xmlpull.v1.XmlPullParser;
157import org.xmlpull.v1.XmlPullParserException;
158
159import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700161import java.io.FileNotFoundException;
162import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700163import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700165import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700166import java.net.InetAddress;
167import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700168import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700169import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700170import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700171import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700172import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700173import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700174import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700175import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700176import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600177import java.util.SortedSet;
178import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
180/**
181 * @hide
182 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800183public class ConnectivityService extends IConnectivityManager.Stub
184 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900185 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Erik Kline7747fd42017-05-12 16:52:48 +0900187 public static final String DIAG_ARG = "--diag";
188 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900189 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900190
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900191 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700192 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Jake Hamby786e71a2014-02-06 14:43:50 -0800194 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900195 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
Jeff Sharkey899223b2012-08-04 15:24:58 -0700197 // TODO: create better separation between radio types and network types
198
Robert Greenwalt42acef32009-08-12 16:08:25 -0700199 // how long to wait before switching back to a radio's default network
200 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
201 // system property that can override the above value
202 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
203 "android.telephony.apn-restore";
204
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900205 // How long to wait before putting up a "This network doesn't have an Internet connection,
206 // connect anyway?" dialog after the user selects a network that doesn't validate.
207 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
208
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900209 // Default to 30s linger time-out. Modifiable only for testing.
210 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
211 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
212 @VisibleForTesting
213 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
214
Jeremy Joslin79294842014-12-03 17:15:28 -0800215 // How long to delay to removal of a pending intent based request.
216 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
217 private final int mReleasePendingIntentDelayMs;
218
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900219 private MockableSystemProperties mSystemProperties;
220
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800221 private Tethering mTethering;
222
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700223 private final PermissionMonitor mPermissionMonitor;
224
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700225 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700226
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700227 @GuardedBy("mVpns")
228 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700229
Hugo Benichi69744342017-11-27 10:57:16 +0900230 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
231 // a direct call to LockdownVpnTracker.isEnabled().
232 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700233 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900234 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700235 private LockdownVpnTracker mLockdownTracker;
236
Erik Klineda4bfa82015-04-30 12:58:40 +0900237 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700239 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700240 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700243 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800246 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900248 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700249
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700250 private String mCurrentTcpBufferSizes;
251
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 private static final int ENABLED = 1;
253 private static final int DISABLED = 0;
254
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900256 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
257 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900258
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Tear down networks that have no chance (e.g. even if validated) of becoming
261 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 // all networks have been rematched against all NetworkRequests.
263 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400264 // Don't reap networks. This should be passed when some networks have not yet been
265 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 DONT_REAP
267 };
268
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900269 private enum UnneededFor {
270 LINGER, // Determine whether this network is unneeded and should be lingered.
271 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
272 }
273
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275 * used internally to change our mobile data enabled flag
276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278
279 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700280 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700281 * from one net to another. Clear happens when we get a new
282 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
283 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286
Robert Greenwalt434203a2010-10-11 16:00:27 -0700287 /**
288 * used internally to reload global proxy settings
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700291
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700292 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400293 * PAC manager has received new port.
294 */
295 private static final int EVENT_PROXY_HAS_CHANGED = 16;
296
Robert Greenwalte049c232014-04-11 15:53:27 -0700297 /**
298 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700299 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700300 */
301 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
302
Robert Greenwalt7b816022014-04-18 15:25:25 -0700303 /**
304 * used internally when registering NetworkAgents
305 * obj = Messenger
306 */
307 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
308
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 /**
310 * used to add a network request
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
314
315 /**
316 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900317 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 * cancel it.
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
322
323 /**
324 * used to add a network listener - no request
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
328
329 /**
330 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400331 * arg1 = UID of caller
332 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
335
Robert Greenwalta67be032014-05-16 15:49:14 -0700336 /**
337 * used internally when registering NetworkFactories
338 * obj = Messenger
339 */
340 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
341
Robert Greenwalt27711812014-06-25 16:45:57 -0700342 /**
343 * used internally to expire a wakelock when transitioning
344 * from one net to another. Expire happens when we fail to find
345 * a new network (typically after 1 minute) -
346 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
347 * a replacement network.
348 */
349 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
350
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700351 /**
352 * Used internally to indicate the system is ready.
353 */
354 private static final int EVENT_SYSTEM_READY = 25;
355
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800356 /**
357 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400358 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 */
360 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
361
362 /**
363 * used to remove a pending intent and its associated network request.
364 * arg1 = UID of caller
365 * obj = PendingIntent
366 */
367 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
368
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900369 /**
370 * used to specify whether a network should be used even if unvalidated.
371 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
372 * arg2 = whether to remember this choice in the future (1 or 0)
373 * obj = network
374 */
375 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
376
377 /**
378 * used to ask the user to confirm a connection to an unvalidated network.
379 * obj = network
380 */
381 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700382
Erik Klineda4bfa82015-04-30 12:58:40 +0900383 /**
384 * used internally to (re)configure mobile data always-on settings.
385 */
386 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
387
Paul Jensen694f2b82015-06-17 14:15:39 -0400388 /**
389 * used to add a network listener with a pending intent
390 * obj = NetworkRequestInfo
391 */
392 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
393
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900394 /**
395 * used to specify whether a network should not be penalized when it becomes unvalidated.
396 */
397 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
398
399 /**
400 * used to trigger revalidation of a network.
401 */
402 private static final int EVENT_REVALIDATE_NETWORK = 36;
403
Erik Klinea24d4592018-01-11 21:07:29 +0900404 // Handle changes in Private DNS settings.
405 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
406
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900407 private static String eventName(int what) {
408 return sMagicDecoderRing.get(what, Integer.toString(what));
409 }
410
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900411 /** Handler thread used for both of the handlers below. */
412 @VisibleForTesting
413 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700414 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700415 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700417 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900418 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419
Mike Lockwood0f79b542009-08-14 14:18:49 -0400420 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800421 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400422
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700423 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700424 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800425 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700426
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400428 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700429 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700430 private boolean mDefaultProxyDisabled = false;
431
Robert Greenwalt434203a2010-10-11 16:00:27 -0700432 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400433 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434
Jason Monk602b2322013-07-03 17:04:33 -0400435 private PacManager mPacManager = null;
436
Erik Klineda4bfa82015-04-30 12:58:40 +0900437 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700438
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400439 private UserManager mUserManager;
440
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700441 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700442 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700443
Robert Greenwalt50393202011-06-21 17:26:14 -0700444 // the set of network types that can only be enabled by system/sig apps
445 List mProtectedNetworks;
446
John Spurlockbf991a82013-06-24 14:20:23 -0400447 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700448
Wink Savilleab9321d2013-06-29 21:10:57 -0700449 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400450
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900451 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900452 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900453 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900454
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700455 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
456 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700457 private final static int MAX_NET_ID = 65535;
458 private int mNextNetId = MIN_NET_ID;
459
Robert Greenwalt34524f02014-05-18 16:22:10 -0700460 // sequence number of NetworkRequests
461 private int mNextNetworkRequestId = 1;
462
Erik Kline7523eb32015-07-09 18:24:03 +0900463 // NetworkRequest activity String log entries.
464 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
465 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
466
Hugo Benichic2ae2872016-07-11 11:05:12 +0900467 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900468 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
470
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900471 private static final int MAX_WAKELOCK_LOGS = 20;
472 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900473 private int mTotalWakelockAcquisitions = 0;
474 private int mTotalWakelockReleases = 0;
475 private long mTotalWakelockDurationMs = 0;
476 private long mMaxWakelockDurationMs = 0;
477 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900478
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700479 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
480 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 private static class ValidationLog {
482 final Network mNetwork;
483 final String mNetworkExtraInfo;
484 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700485
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
487 mNetwork = network;
488 mNetworkExtraInfo = networkExtraInfo;
489 mLog = log;
490 }
491 }
492 private final ArrayDeque<ValidationLog> mValidationLogs =
493 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
494
495 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900496 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700497 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
498 mValidationLogs.removeLast();
499 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400500 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700501 }
502 }
503
Hugo Benichif9fdf872016-07-28 17:53:06 +0900504 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900505
Erik Kline065ab6e2016-10-02 18:02:14 +0900506 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900507 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900508
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700509 /**
510 * Implements support for the legacy "one network per network type" model.
511 *
512 * We used to have a static array of NetworkStateTrackers, one for each
513 * network type, but that doesn't work any more now that we can have,
514 * for example, more that one wifi network. This class stores all the
515 * NetworkAgentInfo objects that support a given type, but the legacy
516 * API will only see the first one.
517 *
518 * It serves two main purposes:
519 *
520 * 1. Provide information about "the network for a given type" (since this
521 * API only supports one).
522 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
523 * the first network for a given type changes, or if the default network
524 * changes.
525 */
526 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900528 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 /**
532 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
533 * Each list holds references to all NetworkAgentInfos that are used to
534 * satisfy requests for that network type.
535 *
536 * This array is built out at startup such that an unsupported network
537 * doesn't get an ArrayList instance, making this a tristate:
538 * unsupported, supported but not active and active.
539 *
540 * The actual lists are populated when we scan the network types that
541 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900542 *
543 * Threading model:
544 * - addSupportedType() is only called in the constructor
545 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
546 * They are therefore not thread-safe with respect to each other.
547 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
548 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
549 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900551 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552
553 public LegacyTypeTracker() {
554 mTypeLists = (ArrayList<NetworkAgentInfo>[])
555 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
556 }
557
558 public void addSupportedType(int type) {
559 if (mTypeLists[type] != null) {
560 throw new IllegalStateException(
561 "legacy list for type " + type + "already initialized");
562 }
563 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
564 }
565
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 public boolean isTypeSupported(int type) {
567 return isNetworkTypeValid(type) && mTypeLists[type] != null;
568 }
569
570 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900571 synchronized (mTypeLists) {
572 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
573 return mTypeLists[type].get(0);
574 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900576 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 }
578
Robert Greenwalt8d482522015-06-24 13:23:42 -0700579 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900580 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700582 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900584 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900585 }
586 }
587
588 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700589 public void add(int type, NetworkAgentInfo nai) {
590 if (!isTypeSupported(type)) {
591 return; // Invalid network type.
592 }
593 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
594
595 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
596 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 return;
598 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900599 synchronized (mTypeLists) {
600 list.add(nai);
601 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900602
603 // 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 +0900604 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700606 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
607 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700609 }
610
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
614 if (list == null || list.isEmpty()) {
615 return;
616 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900617 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618
Hugo Benichi78caa2582016-06-21 09:48:07 +0900619 synchronized (mTypeLists) {
620 if (!list.remove(nai)) {
621 return;
622 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900623 }
624
Robert Greenwalt8d482522015-06-24 13:23:42 -0700625 final DetailedState state = DetailedState.DISCONNECTED;
626
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900627 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 maybeLogBroadcast(nai, state, type, wasDefault);
629 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900630 }
631
632 if (!list.isEmpty() && wasFirstNetwork) {
633 if (DBG) log("Other network available for type " + type +
634 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900635 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700636 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
637 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900638 }
639 }
640
641 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900642 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
643 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700644 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900645 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700646 }
647 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700648
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 // send out another legacy broadcast - currently only used for suspend/unsuspend
650 // toggle
651 public void update(NetworkAgentInfo nai) {
652 final boolean isDefault = isDefaultNetwork(nai);
653 final DetailedState state = nai.networkInfo.getDetailedState();
654 for (int type = 0; type < mTypeLists.length; type++) {
655 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700656 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900657 final boolean isFirst = contains && (nai == list.get(0));
658 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700659 maybeLogBroadcast(nai, state, type, isDefault);
660 sendLegacyNetworkBroadcast(nai, state, type);
661 }
662 }
663 }
664
Lorenzo Colittia793a672014-07-31 23:20:17 +0900665 private String naiToString(NetworkAgentInfo nai) {
666 String name = (nai != null) ? nai.name() : "null";
667 String state = (nai.networkInfo != null) ?
668 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
669 "???/???";
670 return name + " " + state;
671 }
672
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700673 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900674 pw.println("mLegacyTypeTracker:");
675 pw.increaseIndent();
676 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700677 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900678 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700679 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900680 pw.println();
681 pw.println("Current state:");
682 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900683 synchronized (mTypeLists) {
684 for (int type = 0; type < mTypeLists.length; type++) {
685 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
686 for (NetworkAgentInfo nai : mTypeLists[type]) {
687 pw.println(type + " " + naiToString(nai));
688 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900689 }
690 }
691 pw.decreaseIndent();
692 pw.decreaseIndent();
693 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700694 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700695 }
696 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
697
Jeff Sharkey899223b2012-08-04 15:24:58 -0700698 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700699 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900700 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
701 }
702
703 @VisibleForTesting
704 protected ConnectivityService(Context context, INetworkManagementService netManager,
705 INetworkStatsService statsService, INetworkPolicyManager policyManager,
706 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800707 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800708
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900709 mSystemProperties = getSystemProperties();
710
Hugo Benichif9fdf872016-07-28 17:53:06 +0900711 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900712 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900713 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900714 mNetworkRequests.put(mDefaultRequest, defaultNRI);
715 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900716
717 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900718 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700719
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900720 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900721 mHandlerThread.start();
722 mHandler = new InternalHandler(mHandlerThread.getLooper());
723 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700724
Jeremy Joslin79294842014-12-03 17:15:28 -0800725 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
726 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
727
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900728 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900729
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700731 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800732 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700733 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900734 mPolicyManagerInternal = checkNotNull(
735 LocalServices.getService(NetworkPolicyManagerInternal.class),
736 "missing NetworkPolicyManagerInternal");
737
Jeff Sharkey82f85212012-08-24 11:17:25 -0700738 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700739 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700740
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900742 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700743 } catch (RemoteException e) {
744 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700745 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700746 }
747
748 final PowerManager powerManager = (PowerManager) context.getSystemService(
749 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700750 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
751 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
752 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800753 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700754
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700755 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700756
Wink Saville51f456f2013-04-23 14:26:51 -0700757 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900758 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700759 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 String[] naStrings = context.getResources().getStringArray(
761 com.android.internal.R.array.networkAttributes);
762 for (String naString : naStrings) {
763 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700764 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700765 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700766 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800767 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700768 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700770 }
Wink Saville51f456f2013-04-23 14:26:51 -0700771 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
772 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
773 n.type);
774 continue;
775 }
Wink Saville975c8482011-04-07 14:23:45 -0700776 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800777 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700778 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700779 continue;
780 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700781 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700782
Wink Saville975c8482011-04-07 14:23:45 -0700783 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700784 mNetworksDefined++;
785 } catch(Exception e) {
786 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700787 }
788 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700789
790 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
791 if (mNetConfigs[TYPE_VPN] == null) {
792 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
793 // don't need to add TYPE_VPN to mNetConfigs.
794 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
795 mNetworksDefined++; // used only in the log() statement below.
796 }
797
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900798 // Do the same for Ethernet, since it's often not specified in the configs, although many
799 // devices can use it via USB host adapters.
800 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
801 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
802 mNetworksDefined++;
803 }
804
Wink Saville5e56bc52013-07-29 15:00:57 -0700805 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700806
Robert Greenwalt50393202011-06-21 17:26:14 -0700807 mProtectedNetworks = new ArrayList<Integer>();
808 int[] protectedNetworks = context.getResources().getIntArray(
809 com.android.internal.R.array.config_protectedNetworks);
810 for (int p : protectedNetworks) {
811 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
812 mProtectedNetworks.add(p);
813 } else {
814 if (DBG) loge("Ignoring protectedNetwork " + p);
815 }
816 }
817
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900818 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
819 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700820
Erik Kline47222fc2017-04-30 19:36:15 +0900821 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800822
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700823 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
824
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700825 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700826 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100827 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700828 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700829 intentFilter.addAction(Intent.ACTION_USER_ADDED);
830 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000831 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700832 mContext.registerReceiverAsUser(
833 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000834 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
835 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900836
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700837 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700838 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700839 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700840 } catch (RemoteException e) {
841 loge("Error registering observer :" + e);
842 }
843
Erik Klineda4bfa82015-04-30 12:58:40 +0900844 mSettingsObserver = new SettingsObserver(mContext, mHandler);
845 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800846
John Spurlockbf991a82013-06-24 14:20:23 -0400847 mDataConnectionStats = new DataConnectionStats(mContext);
848 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400849
Jason Monkdecd2952013-10-10 14:02:51 -0400850 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700851
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400852 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900853
854 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900855 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
856 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900857
858 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
859 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
860 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
861 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
862 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
863 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
864 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900865
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900866 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900867 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900868 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900869
870 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900871 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700873
Erik Kline47222fc2017-04-30 19:36:15 +0900874 private Tethering makeTethering() {
875 // TODO: Move other elements into @Overridden getters.
876 final TetheringDependencies deps = new TetheringDependencies();
877 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
878 IoThread.get().getLooper(), new MockableSystemProperties(),
879 deps);
880 }
881
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900882 private NetworkRequest createInternetRequestForTransport(
883 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900884 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900885 netCap.addCapability(NET_CAPABILITY_INTERNET);
886 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 if (transportType > -1) {
888 netCap.addTransportType(transportType);
889 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900890 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900891 }
892
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900893 // Used only for testing.
894 // TODO: Delete this and either:
895 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
896 // changing ContentResolver to make registerContentObserver non-final).
897 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
898 // by subclassing SettingsObserver.
899 @VisibleForTesting
900 void updateMobileDataAlwaysOn() {
901 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
902 }
903
Erik Klineda4bfa82015-04-30 12:58:40 +0900904 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900905 final boolean enable = toBool(Settings.Global.getInt(
906 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900907 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
908 if (enable == isEnabled) {
909 return; // Nothing to do.
910 }
911
912 if (enable) {
913 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900914 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900915 } else {
916 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
917 }
918 }
919
920 private void registerSettingsCallbacks() {
921 // Watch for global HTTP proxy changes.
922 mSettingsObserver.observe(
923 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
924 EVENT_APPLY_GLOBAL_HTTP_PROXY);
925
926 // Watch for whether or not to keep mobile data always on.
927 mSettingsObserver.observe(
928 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
929 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
930 }
931
Erik Klinea24d4592018-01-11 21:07:29 +0900932 private void registerPrivateDnsSettingsCallbacks() {
933 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
934 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
935 }
936 }
937
Robert Greenwalt34524f02014-05-18 16:22:10 -0700938 private synchronized int nextNetworkRequestId() {
939 return mNextNetworkRequestId++;
940 }
941
Paul Jensen67b0b072015-06-10 11:22:17 -0400942 @VisibleForTesting
943 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400944 synchronized (mNetworkForNetId) {
945 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
946 int netId = mNextNetId;
947 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
948 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500949 if (!mNetIdInUse.get(netId)) {
950 mNetIdInUse.put(netId, true);
951 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400952 }
953 }
954 }
955 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700956 }
957
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600958 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600960 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
961 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600963 state = nai.getNetworkState();
964 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600966 final NetworkInfo info = new NetworkInfo(networkType, 0,
967 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
969 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700970 final NetworkCapabilities capabilities = new NetworkCapabilities();
971 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
972 !info.isRoaming());
973 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600974 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600976 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600977 return state;
978 } else {
979 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800980 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400981 }
982
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
984 if (network == null) {
985 return null;
986 }
987 synchronized (mNetworkForNetId) {
988 return mNetworkForNetId.get(network.netId);
989 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900992 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +0900993 synchronized (mVpns) {
994 if (!mLockdownEnabled) {
995 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900996 Vpn vpn = mVpns.get(user);
997 if (vpn != null && vpn.appliesToUid(uid)) {
998 return vpn.getUnderlyingNetworks();
999 }
1000 }
1001 }
1002 return null;
1003 }
1004
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001005 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001006 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001007
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001008 final Network[] networks = getVpnUnderlyingNetworks(uid);
1009 if (networks != null) {
1010 // getUnderlyingNetworks() returns:
1011 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1012 // empty array => the VPN explicitly said "no default network".
1013 // non-empty array => the VPN specified one or more default networks; we use the
1014 // first one.
1015 if (networks.length > 0) {
1016 nai = getNetworkAgentInfoForNetwork(networks[0]);
1017 } else {
1018 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001019 }
1020 }
1021
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001023 return nai.getNetworkState();
1024 } else {
1025 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001027 }
1028
1029 /**
1030 * Check if UID should be blocked from using the network with the given LinkProperties.
1031 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001032 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1033 boolean ignoreBlocked) {
1034 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001035 if (ignoreBlocked) {
1036 return false;
1037 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001038 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001039 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1040 if (isSystem(uid)) {
1041 return false;
1042 }
Robin Lee17e61832016-05-09 13:46:28 +01001043 synchronized (mVpns) {
1044 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1045 if (vpn != null && vpn.isBlockingUid(uid)) {
1046 return true;
1047 }
1048 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001049 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001050 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
1052
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001053 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001054 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1055 return;
1056 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001057 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001058 synchronized (mBlockedAppUids) {
1059 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001060 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001061 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001062 blocked = false;
1063 } else {
1064 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001065 }
1066 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001067 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1068 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1069 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001070 }
1071
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001072 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1074 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001075 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001077 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1079
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001080 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001082 }
Hugo Benichi69744342017-11-27 10:57:16 +09001083 synchronized (mVpns) {
1084 if (mLockdownTracker != null) {
1085 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1086 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001087 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 }
1089
1090 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 * Return NetworkInfo for the active (i.e., connected) network interface.
1092 * It is assumed that at most one network is active at a time. If more
1093 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001094 * @return the info for the active network, or {@code null} if none is
1095 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001097 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 enforceAccessPermission();
1100 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001103 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1104 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106
Paul Jensen31a94f42015-02-13 14:18:39 -05001107 @Override
1108 public Network getActiveNetwork() {
1109 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001111 }
1112
1113 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001115 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001117 }
1118
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001120 final int user = UserHandle.getUserId(uid);
1121 int vpnNetId = NETID_UNSET;
1122 synchronized (mVpns) {
1123 final Vpn vpn = mVpns.get(user);
1124 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1125 }
1126 NetworkAgentInfo nai;
1127 if (vpnNetId != NETID_UNSET) {
1128 synchronized (mNetworkForNetId) {
1129 nai = mNetworkForNetId.get(vpnNetId);
1130 }
1131 if (nai != null) return nai.network;
1132 }
1133 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 if (nai != null
1135 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1136 nai = null;
1137 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001138 return nai != null ? nai.network : null;
1139 }
1140
Lorenzo Colitti18660282016-07-04 12:55:44 +09001141 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001142 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1143 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144 final int uid = Binder.getCallingUid();
1145 NetworkState state = getUnfilteredActiveNetworkState(uid);
1146 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 }
1148
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001150 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001152 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 }
1156
1157 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 public NetworkInfo getNetworkInfo(int networkType) {
1159 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001161 if (getVpnUnderlyingNetworks(uid) != null) {
1162 // A VPN is active, so we may need to return one of its underlying networks. This
1163 // information is not available in LegacyTypeTracker, so we have to get it from
1164 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001166 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001169 }
1170 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 return state.networkInfo;
1183 } else {
1184 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001185 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 }
1187
1188 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 public NetworkInfo[] getAllNetworkInfo() {
1190 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001191 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001192 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1193 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001194 NetworkInfo info = getNetworkInfo(networkType);
1195 if (info != null) {
1196 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001202 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001203 public Network getNetworkForType(int networkType) {
1204 enforceAccessPermission();
1205 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001206 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1207 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001209 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001211 }
1212
1213 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 public Network[] getAllNetworks() {
1215 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001216 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001217 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001219 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001221 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 }
1224
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001225 @Override
1226 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1227 // The basic principle is: if an app's traffic could possibly go over a
1228 // network, without the app doing anything multinetwork-specific,
1229 // (hence, by "default"), then include that network's capabilities in
1230 // the array.
1231 //
1232 // In the normal case, app traffic only goes over the system's default
1233 // network connection, so that's the only network returned.
1234 //
1235 // With a VPN in force, some app traffic may go into the VPN, and thus
1236 // over whatever underlying networks the VPN specifies, while other app
1237 // traffic may go over the system default network (e.g.: a split-tunnel
1238 // VPN, or an app disallowed by the VPN), so the set of networks
1239 // returned includes the VPN's underlying networks and the system
1240 // default.
1241 enforceAccessPermission();
1242
1243 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1244
1245 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001246 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001247 if (nc != null) {
1248 result.put(nai.network, nc);
1249 }
1250
Hugo Benichi69744342017-11-27 10:57:16 +09001251 synchronized (mVpns) {
1252 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001253 Vpn vpn = mVpns.get(userId);
1254 if (vpn != null) {
1255 Network[] networks = vpn.getUnderlyingNetworks();
1256 if (networks != null) {
1257 for (Network network : networks) {
1258 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001259 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001260 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001261 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001262 }
1263 }
1264 }
1265 }
1266 }
1267 }
1268
1269 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1270 out = result.values().toArray(out);
1271 return out;
1272 }
1273
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001275 public boolean isNetworkSupported(int networkType) {
1276 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001277 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001278 }
1279
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 /**
1281 * Return LinkProperties for the active (i.e., connected) default
1282 * network interface. It is assumed that at most one default network
1283 * is active at a time. If more than one is active, it is indeterminate
1284 * which will be returned.
1285 * @return the ip properties for the active network, or {@code null} if
1286 * none is active
1287 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001288 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001289 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001290 enforceAccessPermission();
1291 final int uid = Binder.getCallingUid();
1292 NetworkState state = getUnfilteredActiveNetworkState(uid);
1293 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001294 }
1295
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001296 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001297 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001299 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1300 if (nai != null) {
1301 synchronized (nai) {
1302 return new LinkProperties(nai.linkProperties);
1303 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 }
1305 return null;
1306 }
1307
Robert Greenwalt12e67352014-05-13 21:41:06 -07001308 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001309 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001310 public LinkProperties getLinkProperties(Network network) {
1311 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001312 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1313 }
1314
1315 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1316 if (nai == null) {
1317 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001318 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001319 synchronized (nai) {
1320 return new LinkProperties(nai.linkProperties);
1321 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001322 }
1323
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001324 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 if (nai != null) {
1326 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001327 if (nai.networkCapabilities != null) {
1328 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001329 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001330 }
1331 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001332 return null;
1333 }
1334
1335 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001336 public NetworkCapabilities getNetworkCapabilities(Network network) {
1337 enforceAccessPermission();
1338 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1339 }
1340
1341 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001342 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001343 // Require internal since we're handing out IMSI details
1344 enforceConnectivityInternalPermission();
1345
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001346 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001347 for (Network network : getAllNetworks()) {
1348 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1349 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001350 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001351 }
1352 }
1353 return result.toArray(new NetworkState[result.size()]);
1354 }
1355
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001356 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001357 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001358 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001359 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1360 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1361 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001362 }
1363
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001364 @Override
1365 public boolean isActiveNetworkMetered() {
1366 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001367
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001368 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1369 if (caps != null) {
1370 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1371 } else {
1372 // Always return the most conservative value
1373 return true;
1374 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001375 }
1376
Jeff Sharkey216c1812012-08-05 14:29:23 -07001377 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1378 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001379 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001380 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001381 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001382 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001383 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001384
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 * Ensure that a network route exists to deliver traffic to the specified
1387 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001388 * @param networkType the type of the network over which traffic to the
1389 * specified host is to be routed
1390 * @param hostAddress the IP address of the host to which the route is
1391 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 * @return {@code true} on success, {@code false} on failure
1393 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001394 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001395 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001397 if (mProtectedNetworks.contains(networkType)) {
1398 enforceConnectivityInternalPermission();
1399 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001400
Chad Brubakerc0234532014-02-14 13:24:29 -08001401 InetAddress addr;
1402 try {
1403 addr = InetAddress.getByAddress(hostAddress);
1404 } catch (UnknownHostException e) {
1405 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1406 return false;
1407 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001410 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 return false;
1412 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001413
1414 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1415 if (nai == null) {
1416 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1417 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1418 } else {
1419 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1420 }
1421 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001422 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001423
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001424 DetailedState netState;
1425 synchronized (nai) {
1426 netState = nai.networkInfo.getDetailedState();
1427 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001428
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001429 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001430 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001431 log("requestRouteToHostAddress on down network "
1432 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001433 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001434 }
1435 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001438 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001439 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001440 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001441 LinkProperties lp;
1442 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001443 synchronized (nai) {
1444 lp = nai.linkProperties;
1445 netId = nai.network.netId;
1446 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001447 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001448 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1449 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001450 } finally {
1451 Binder.restoreCallingIdentity(token);
1452 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001453 }
1454
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001455 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001456 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001457 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001458 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001460 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001461 if (bestRoute.getGateway().equals(addr)) {
1462 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001463 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001464 } else {
1465 // if we will connect to this through another route, add a direct route
1466 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001467 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 }
1469 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001470 if (DBG) log("Adding legacy route " + bestRoute +
1471 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001472 try {
1473 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1474 } catch (Exception e) {
1475 // never crash - catch them all
1476 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001477 return false;
1478 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001479 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481
Jeff Sharkey75d31892018-01-18 22:01:59 +09001482 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001483 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001484 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001485 // TODO: notify UID when it has requested targeted updates
1486 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001487 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001488 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001489 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001490 if (restrictBackground) {
1491 log("onRestrictBackgroundChanged(true): disabling tethering");
1492 mTethering.untetherAll();
1493 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001494 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 };
1496
Robin Lee3b3dd942015-05-12 18:14:58 +01001497 /**
1498 * Require that the caller is either in the same user or has appropriate permission to interact
1499 * across users.
1500 *
1501 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1502 */
1503 private void enforceCrossUserPermission(int userId) {
1504 if (userId == UserHandle.getCallingUserId()) {
1505 // Not a cross-user call.
1506 return;
1507 }
1508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1510 "ConnectivityService");
1511 }
1512
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001513 private void enforceInternetPermission() {
1514 mContext.enforceCallingOrSelfPermission(
1515 android.Manifest.permission.INTERNET,
1516 "ConnectivityService");
1517 }
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.ACCESS_NETWORK_STATE,
1522 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524
1525 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001526 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528
Charles Hea0a87e82017-05-15 17:07:18 +01001529 private void enforceSettingsPermission() {
1530 mContext.enforceCallingOrSelfPermission(
1531 android.Manifest.permission.NETWORK_SETTINGS,
1532 "ConnectivityService");
1533 }
1534
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001535 private void enforceTetherAccessPermission() {
1536 mContext.enforceCallingOrSelfPermission(
1537 android.Manifest.permission.ACCESS_NETWORK_STATE,
1538 "ConnectivityService");
1539 }
1540
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001541 private void enforceConnectivityInternalPermission() {
1542 mContext.enforceCallingOrSelfPermission(
1543 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1544 "ConnectivityService");
1545 }
1546
Hugo Benichi514da602016-07-19 15:59:27 +09001547 private void enforceConnectivityRestrictedNetworksPermission() {
1548 try {
1549 mContext.enforceCallingOrSelfPermission(
1550 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1551 "ConnectivityService");
1552 return;
1553 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1554 enforceConnectivityInternalPermission();
1555 }
1556
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001557 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001558 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001559 }
1560
Lorenzo Colitti18660282016-07-04 12:55:44 +09001561 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001562 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001563 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001564 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001565 }
1566
1567 private void sendInetConditionBroadcast(NetworkInfo info) {
1568 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1569 }
1570
Wink Saville628b0852011-08-04 15:01:58 -07001571 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001572 synchronized (mVpns) {
1573 if (mLockdownTracker != null) {
1574 info = new NetworkInfo(info);
1575 mLockdownTracker.augmentNetworkInfo(info);
1576 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001577 }
1578
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001579 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001580 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001581 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if (info.isFailover()) {
1583 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1584 info.setFailover(false);
1585 }
1586 if (info.getReason() != null) {
1587 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1588 }
1589 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001590 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1591 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001593 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001594 return intent;
1595 }
1596
1597 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1598 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1599 }
1600
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001601 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001602 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1603 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1604 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001605 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001606 final long ident = Binder.clearCallingIdentity();
1607 try {
1608 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1609 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1610 } finally {
1611 Binder.restoreCallingIdentity(ident);
1612 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001613 }
1614
Mike Lockwood0f79b542009-08-14 14:18:49 -04001615 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001616 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001617 if (!mSystemReady) {
1618 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001619 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001620 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001621 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001622 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001623 }
1624
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001625 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001626 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001627 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001628 final NetworkInfo ni = intent.getParcelableExtra(
1629 ConnectivityManager.EXTRA_NETWORK_INFO);
1630 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1631 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1632 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001633 } else {
1634 BroadcastOptions opts = BroadcastOptions.makeBasic();
1635 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1636 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001637 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001638 final IBatteryStats bs = BatteryStatsService.getService();
1639 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001640 bs.noteConnectivityChanged(intent.getIntExtra(
1641 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1642 ni != null ? ni.getState().toString() : "?");
1643 } catch (RemoteException e) {
1644 }
1645 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001646 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001647 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001648 } finally {
1649 Binder.restoreCallingIdentity(ident);
1650 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001651 }
1652 }
1653
1654 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001655 loadGlobalProxy();
1656
Hugo Benichi20035e02017-04-26 14:53:28 +09001657 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001658 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001659 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001660 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001661 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001662 }
1663 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001664 // load the global proxy at startup
1665 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001666
Robin Lee244ce8e2016-01-05 18:03:46 +00001667 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1668 // for user to unlock device too.
1669 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001670
Erik Klineda4bfa82015-04-30 12:58:40 +09001671 // Configure whether mobile data is always on.
1672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1673
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001674 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001675
1676 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001680 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001681 *
1682 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001683 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001684 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001685 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1686 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001687
1688 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001689 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001690
Robert Greenwalt7b816022014-04-18 15:25:25 -07001691 if (networkAgent.networkCapabilities.hasTransport(
1692 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001693 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1694 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001695 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001696 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001697 } else if (networkAgent.networkCapabilities.hasTransport(
1698 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001699 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1700 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001701 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001702 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001703 } else {
1704 // do not track any other networks
1705 timeout = 0;
1706 }
1707
Robert Greenwalt7b816022014-04-18 15:25:25 -07001708 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001709 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001710 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001711 } catch (Exception e) {
1712 // You shall not crash!
1713 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001714 }
1715 }
1716 }
1717
1718 /**
1719 * Remove data activity tracking when network disconnects.
1720 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1722 final String iface = networkAgent.linkProperties.getInterfaceName();
1723 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001724
Robert Greenwalt7b816022014-04-18 15:25:25 -07001725 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1726 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001727 try {
1728 // the call fails silently if no idletimer setup for this interface
1729 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001730 } catch (Exception e) {
1731 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001732 }
1733 }
1734 }
1735
1736 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001737 * Reads the network specific MTU size from reources.
1738 * and set it on it's iface.
1739 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1741 final String iface = newLp.getInterfaceName();
1742 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001743 if (oldLp == null && mtu == 0) {
1744 // Silently ignore unset MTU value.
1745 return;
1746 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001747 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1748 if (VDBG) log("identical MTU - not setting");
1749 return;
1750 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001751 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001752 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 return;
1754 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001755
w1997615afd812014-08-05 15:18:11 -07001756 // Cannot set MTU without interface name
1757 if (TextUtils.isEmpty(iface)) {
1758 loge("Setting MTU size with null iface.");
1759 return;
1760 }
1761
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001763 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 mNetd.setMtu(iface, mtu);
1765 } catch (Exception e) {
1766 Slog.e(TAG, "exception in setMtu()" + e);
1767 }
1768 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001769
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001770 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001771 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1772
1773 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001774 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001775 protected MockableSystemProperties getSystemProperties() {
1776 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001777 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001778
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001779 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1780 if (isDefaultNetwork(nai) == false) {
1781 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001782 }
1783
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001784 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1785 String[] values = null;
1786 if (tcpBufferSizes != null) {
1787 values = tcpBufferSizes.split(",");
1788 }
1789
1790 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001791 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001792 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1793 values = tcpBufferSizes.split(",");
1794 }
1795
1796 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1797
1798 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001799 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001800
1801 final String prefix = "/sys/kernel/ipv4/tcp_";
1802 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1803 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1804 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1805 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1806 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1807 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1808 mCurrentTcpBufferSizes = tcpBufferSizes;
1809 } catch (IOException e) {
1810 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001811 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001812
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001813 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001814 Settings.Global.TCP_DEFAULT_INIT_RWND,
1815 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001816 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1817 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001818 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001819 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001820 }
1821
Robert Greenwalt562cc542014-05-15 18:07:26 -07001822 @Override
1823 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001824 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001825 NETWORK_RESTORE_DELAY_PROP_NAME);
1826 if(restoreDefaultNetworkDelayStr != null &&
1827 restoreDefaultNetworkDelayStr.length() != 0) {
1828 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001829 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001830 } catch (NumberFormatException e) {
1831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001833 // if the system property isn't set, use the value for the apn type
1834 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1835
1836 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1837 (mNetConfigs[networkType] != null)) {
1838 ret = mNetConfigs[networkType].restoreTime;
1839 }
1840 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001843 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001844 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001845 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001846 }
1847 return false;
1848 }
1849
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001850 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1851 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1852 final long DIAG_TIME_MS = 5000;
1853 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1854 // Start gathering diagnostic information.
1855 netDiags.add(new NetworkDiagnostics(
1856 nai.network,
1857 new LinkProperties(nai.linkProperties), // Must be a copy.
1858 DIAG_TIME_MS));
1859 }
1860
1861 for (NetworkDiagnostics netDiag : netDiags) {
1862 pw.println();
1863 netDiag.waitForMeasurements();
1864 netDiag.dump(pw);
1865 }
1866 }
1867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001869 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1870 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001871 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001872
Erik Kline7747fd42017-05-12 16:52:48 +09001873 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001874 dumpNetworkDiagnostics(pw);
1875 return;
Erik Klineee363c42017-05-29 09:11:03 +09001876 } else if (argsContain(args, TETHERING_ARG)) {
1877 mTethering.dump(fd, pw, args);
1878 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001879 }
Erik Kline379747a2015-06-05 17:47:34 +09001880
Lorenzo Colittie3805462015-06-03 11:18:24 +09001881 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001882 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001883 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001884 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001885 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001886 pw.println();
1887
Paul Jensen85cf78e2015-06-25 13:25:07 -04001888 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001889 pw.print("Active default network: ");
1890 if (defaultNai == null) {
1891 pw.println("none");
1892 } else {
1893 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001895 pw.println();
1896
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001897 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001898 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001899 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1900 pw.println(nai.toString());
1901 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001902 pw.println(String.format(
1903 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1904 nai.numForegroundNetworkRequests(),
1905 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1906 nai.numBackgroundNetworkRequests(),
1907 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001908 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001909 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1910 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001911 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001912 pw.decreaseIndent();
1913 pw.println("Lingered:");
1914 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001915 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001916 pw.decreaseIndent();
1917 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001918 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001919 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001920 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001921
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001923 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001924 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1925 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001926 }
1927 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001928 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001929
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001930 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001931
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001932 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001933 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001934
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001935 pw.println();
1936 mKeepaliveTracker.dump(pw);
1937
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001938 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001939 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001940
Erik Kline7747fd42017-05-12 16:52:48 +09001941 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001942 pw.println();
1943 synchronized (mValidationLogs) {
1944 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001945 for (ValidationLog p : mValidationLogs) {
1946 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001947 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001948 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001949 pw.decreaseIndent();
1950 }
1951 }
Erik Kline7523eb32015-07-09 18:24:03 +09001952
1953 pw.println();
1954 pw.println("mNetworkRequestInfoLogs (most recent first):");
1955 pw.increaseIndent();
1956 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1957 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001958
1959 pw.println();
1960 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1961 pw.increaseIndent();
1962 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1963 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001964
1965 pw.println();
1966 pw.println("NetTransition WakeLock activity (most recent first):");
1967 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001968 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1969 pw.println("total releases: " + mTotalWakelockReleases);
1970 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1971 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1972 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1973 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1974 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1975 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001976 mWakelockLogs.reverseDump(fd, pw, args);
1977 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
1980
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001981 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001982 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001983 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001984 if (officialNai != null && officialNai.equals(nai)) return true;
1985 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001986 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001987 " - " + nai);
1988 }
1989 return false;
1990 }
1991
Robert Greenwalt42acef32009-08-12 16:08:25 -07001992 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001993 private class NetworkStateTrackerHandler extends Handler {
1994 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001995 super(looper);
1996 }
1997
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001998 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002000 default:
2001 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002002 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002003 handleAsyncChannelHalfConnect(msg);
2004 break;
2005 }
2006 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2007 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2008 if (nai != null) nai.asyncChannel.disconnect();
2009 break;
2010 }
2011 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2012 handleAsyncChannelDisconnected(msg);
2013 break;
2014 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002015 }
2016 return true;
2017 }
2018
2019 private void maybeHandleNetworkAgentMessage(Message msg) {
2020 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2021 if (nai == null) {
2022 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002023 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002024 }
2025 return;
2026 }
2027
2028 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002029 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2031 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002032 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2033 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002034 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002035 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002036 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002037 break;
2038 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002040 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 break;
2042 }
2043 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002045 updateNetworkInfo(nai, info);
2046 break;
2047 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002048 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002049 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002050 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002051 break;
2052 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002053 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002054 try {
2055 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002056 } catch (Exception e) {
2057 // Never crash!
2058 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002059 }
2060 break;
2061 }
2062 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002063 try {
2064 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002065 } catch (Exception e) {
2066 // Never crash!
2067 loge("Exception in removeVpnUidRanges: " + e);
2068 }
2069 break;
2070 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002071 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002072 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2073 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002074 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002075 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002076 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002077 break;
2078 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002079 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002080 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2081 break;
2082 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002083 }
2084 }
2085
2086 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2087 switch (msg.what) {
2088 default:
2089 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002090 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002091 final NetworkAgentInfo nai;
2092 synchronized (mNetworkForNetId) {
2093 nai = mNetworkForNetId.get(msg.arg2);
2094 }
Erik Klinea24d4592018-01-11 21:07:29 +09002095 if (nai == null) break;
2096
2097 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2098 final boolean wasValidated = nai.lastValidated;
2099 final boolean wasDefault = isDefaultNetwork(nai);
2100
2101 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2102 ? (PrivateDnsConfig) msg.obj : null;
2103 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2104
2105 final boolean reevaluationRequired;
2106 final String logMsg;
2107 if (valid) {
2108 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2109 logMsg = (DBG && (privateDnsCfg != null))
2110 ? " with " + privateDnsCfg.toString() : "";
2111 } else {
2112 reevaluationRequired = false;
2113 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2114 ? " with redirect to " + redirectUrl : "";
2115 }
2116 if (DBG) {
2117 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2118 }
2119 // If there is a change in Private DNS configuration,
2120 // trigger reevaluation of the network to test it.
2121 if (reevaluationRequired) {
2122 nai.networkMonitor.sendMessage(
2123 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2124 break;
2125 }
2126 if (valid != nai.lastValidated) {
2127 if (wasDefault) {
2128 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2129 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002130 }
Erik Klinea24d4592018-01-11 21:07:29 +09002131 final int oldScore = nai.getCurrentScore();
2132 nai.lastValidated = valid;
2133 nai.everValidated |= valid;
2134 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2135 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2136 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2137 }
2138 updateInetCondition(nai);
2139 // Let the NetworkAgent know the state of its network
2140 Bundle redirectUrlBundle = new Bundle();
2141 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2142 nai.asyncChannel.sendMessage(
2143 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2144 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2145 0, redirectUrlBundle);
2146 if (wasValidated && !nai.lastValidated) {
2147 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002148 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 break;
2150 }
Paul Jensen869868be2014-05-15 10:33:05 -04002151 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002152 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002153 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002154 final NetworkAgentInfo nai;
2155 synchronized (mNetworkForNetId) {
2156 nai = mNetworkForNetId.get(netId);
2157 }
Calvin Onbe96da12016-10-11 15:10:46 -07002158 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002159 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002160 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002161 nai.lastCaptivePortalDetected = visible;
2162 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002163 if (nai.lastCaptivePortalDetected &&
2164 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2165 if (DBG) log("Avoiding captive portal network: " + nai.name());
2166 nai.asyncChannel.sendMessage(
2167 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2168 teardownUnneededNetwork(nai);
2169 break;
2170 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002171 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002172 }
2173 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002174 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002175 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002176 if (nai == null) {
2177 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2178 break;
2179 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002180 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002181 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002182 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002183 }
Paul Jensen869868be2014-05-15 10:33:05 -04002184 }
Paul Jensen869868be2014-05-15 10:33:05 -04002185 break;
2186 }
Erik Klinea24d4592018-01-11 21:07:29 +09002187 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2188 final NetworkAgentInfo nai;
2189 synchronized (mNetworkForNetId) {
2190 nai = mNetworkForNetId.get(msg.arg2);
2191 }
2192 if (nai == null) break;
2193
2194 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2195 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2196 if (nai.lastValidated && reevaluationRequired) {
2197 nai.networkMonitor.sendMessage(
2198 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2199 }
2200 break;
2201 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002202 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002203 return true;
2204 }
2205
Calvin Onbe96da12016-10-11 15:10:46 -07002206 private int getCaptivePortalMode() {
2207 return Settings.Global.getInt(mContext.getContentResolver(),
2208 Settings.Global.CAPTIVE_PORTAL_MODE,
2209 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2210 }
2211
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002212 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2213 switch (msg.what) {
2214 default:
2215 return false;
2216 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2217 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2218 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2219 handleLingerComplete(nai);
2220 }
2221 break;
2222 }
2223 }
2224 return true;
2225 }
2226
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002227 @Override
2228 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002229 if (!maybeHandleAsyncChannelMessage(msg) &&
2230 !maybeHandleNetworkMonitorMessage(msg) &&
2231 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002232 maybeHandleNetworkAgentMessage(msg);
2233 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002234 }
2235 }
2236
Erik Klinea24d4592018-01-11 21:07:29 +09002237 private void handlePrivateDnsSettingsChanged() {
2238 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2239
2240 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2241 // Private DNS only ever applies to networks that might provide
2242 // Internet access and therefore also require validation.
2243 if (!NetworkMonitor.isValidationRequired(
2244 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2245 continue;
2246 }
2247
2248 // Notify the NetworkMonitor thread in case it needs to cancel or
2249 // schedule DNS resolutions. If a DNS resolution is required the
2250 // result will be sent back to us.
2251 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2252
2253 if (!cfg.inStrictMode()) {
2254 // No strict mode hostname DNS resolution needed, so just update
2255 // DNS settings directly. In opportunistic and "off" modes this
2256 // just reprograms netd with the network-supplied DNS servers
2257 // (and of course the boolean of whether or not to attempt TLS).
2258 //
2259 // TODO: Consider code flow parity with strict mode, i.e. having
2260 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2261 // performing this call at that time.
2262 updatePrivateDns(nai, cfg);
2263 }
2264 }
2265 }
2266
2267 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2268 final boolean reevaluationRequired = true;
2269 final boolean dontReevaluate = false;
2270
2271 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2272 updateDnses(nai.linkProperties, null, nai.network.netId);
2273
2274 if (newCfg == null) {
2275 if (oldCfg == null) return dontReevaluate;
2276 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2277 }
2278
2279 if (oldCfg == null) {
2280 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2281 }
2282
2283 if (oldCfg.useTls != newCfg.useTls) {
2284 return reevaluationRequired;
2285 }
2286
2287 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2288 return reevaluationRequired;
2289 }
2290
2291 return dontReevaluate;
2292 }
2293
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 private void updateLingerState(NetworkAgentInfo nai, long now) {
2295 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2296 // 2. If the network was lingering and there are now requests, unlinger it.
2297 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2298 // one lingered request, start lingering.
2299 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002300 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002301 if (DBG) log("Unlingering " + nai.name());
2302 nai.unlinger();
2303 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002304 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002305 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002306 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 nai.linger();
2308 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2309 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2310 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002311 }
2312
Robert Greenwalt7b816022014-04-18 15:25:25 -07002313 private void handleAsyncChannelHalfConnect(Message msg) {
2314 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002315 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002316 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2317 if (VDBG) log("NetworkFactory connected");
2318 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002319 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002320 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002321 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002322 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002323 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002324 }
2325 } else {
2326 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002327 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002328 }
2329 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2330 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2331 if (VDBG) log("NetworkAgent connected");
2332 // A network agent has requested a connection. Establish the connection.
2333 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2334 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2335 } else {
2336 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002337 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002338 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002339 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002340 synchronized (mNetworkForNetId) {
2341 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002342 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002343 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002344 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002345 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002347 }
2348 }
2349 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002350
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 private void handleAsyncChannelDisconnected(Message msg) {
2352 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2353 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002355 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002356 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002357 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002358 // TODO - if we move the logic to the network agent (have them disconnect
2359 // because they lost all their requests or because their score isn't good)
2360 // then they would disconnect organically, report their new state and then
2361 // disconnect the channel.
2362 if (nai.networkInfo.isConnected()) {
2363 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2364 null, null);
2365 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 final boolean wasDefault = isDefaultNetwork(nai);
2367 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002368 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002369 // Log default network disconnection before required book-keeping.
2370 // Let rematchAllNetworksAndRequests() below record a new default network event
2371 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2372 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002373 long now = SystemClock.elapsedRealtime();
2374 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002375 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002376 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002377 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2378 // by other networks that are already connected. Perhaps that can be done by
2379 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2380 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002382 mKeepaliveTracker.handleStopAllKeepalives(nai,
2383 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002384 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2385 // Disable wakeup packet monitoring for each interface.
2386 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2387 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002388 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002389 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002390 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002391 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002392 // Remove the NetworkAgent, but don't mark the netId as
2393 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002394 mNetworkForNetId.remove(nai.network.netId);
2395 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002396 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002397 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2398 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002399 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002400 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002401 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002402 sendUpdatedScoreToFactories(request, 0);
2403 }
2404 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002405 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002406 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002408 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002409 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002410 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002411 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002412 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002413 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002414 if (nai.created) {
2415 // Tell netd to clean up the configuration for this network
2416 // (routing rules, DNS, etc).
2417 // This may be slow as it requires a lot of netd shelling out to ip and
2418 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2419 // after we've rematched networks with requests which should make a potential
2420 // fallback network the default or requested a new network from the
2421 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2422 // long time.
2423 try {
2424 mNetd.removeNetwork(nai.network.netId);
2425 } catch (Exception e) {
2426 loge("Exception removing network: " + e);
2427 }
Erik Klinea24d4592018-01-11 21:07:29 +09002428 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002429 }
2430 synchronized (mNetworkForNetId) {
2431 mNetIdInUse.delete(nai.network.netId);
2432 }
2433 } else {
2434 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2435 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002436 }
2437 }
2438
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002439 // If this method proves to be too slow then we can maintain a separate
2440 // pendingIntent => NetworkRequestInfo map.
2441 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2442 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2443 Intent intent = pendingIntent.getIntent();
2444 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2445 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2446 if (existingPendingIntent != null &&
2447 existingPendingIntent.getIntent().filterEquals(intent)) {
2448 return entry.getValue();
2449 }
2450 }
2451 return null;
2452 }
2453
2454 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2455 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2456
2457 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2458 if (existingRequest != null) { // remove the existing request.
2459 if (DBG) log("Replacing " + existingRequest.request + " with "
2460 + nri.request + " because their intents matched.");
2461 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2462 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002463 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002464 }
2465
Erik Klineda4bfa82015-04-30 12:58:40 +09002466 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002467 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002468 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002469 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002470 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002471 if (nri.request.networkCapabilities.hasSignalStrength() &&
2472 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2473 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002474 }
2475 }
2476 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002477 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002478 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002479 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002480 }
2481 }
2482
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2484 int callingUid) {
2485 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2486 if (nri != null) {
2487 handleReleaseNetworkRequest(nri.request, callingUid);
2488 }
2489 }
2490
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002491 // Determines whether the network is the best (or could become the best, if it validated), for
2492 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2493 // on the value of reason:
2494 //
2495 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2496 // then it should be torn down.
2497 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2498 // then it should be lingered.
2499 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2500 final int numRequests;
2501 switch (reason) {
2502 case TEARDOWN:
2503 numRequests = nai.numRequestNetworkRequests();
2504 break;
2505 case LINGER:
2506 numRequests = nai.numForegroundNetworkRequests();
2507 break;
2508 default:
2509 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2510 return true;
2511 }
2512
2513 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002514 return false;
2515 }
Paul Jensene0988542015-06-25 15:30:08 -04002516 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002517 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2518 // Background requests don't affect lingering.
2519 continue;
2520 }
2521
Paul Jensene0988542015-06-25 15:30:08 -04002522 // If this Network is already the highest scoring Network for a request, or if
2523 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002524 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002525 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002526 // Note that this catches two important cases:
2527 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2528 // is currently satisfying the request. This is desirable when
2529 // cellular ends up validating but WiFi does not.
2530 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002531 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002532 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002533 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002534 nai.getCurrentScoreAsValidated())) {
2535 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002536 }
2537 }
Paul Jensene0988542015-06-25 15:30:08 -04002538 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002539 }
2540
Erik Klineacdd6392016-07-07 16:50:58 +09002541 private NetworkRequestInfo getNriForAppRequest(
2542 NetworkRequest request, int callingUid, String requestedOperation) {
2543 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2544
Robert Greenwalt9258c642014-03-26 16:47:06 -07002545 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002546 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002547 log(String.format("UID %d attempted to %s for unowned request %s",
2548 callingUid, requestedOperation, nri));
2549 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002550 }
Erik Klineacdd6392016-07-07 16:50:58 +09002551 }
2552
2553 return nri;
2554 }
2555
Erik Kline57faba92015-11-25 12:49:38 +09002556 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002557 if (mNetworkRequests.get(nri.request) == null) {
2558 return;
Erik Kline57faba92015-11-25 12:49:38 +09002559 }
Hugo Benichicd952782017-09-20 11:20:14 +09002560 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002561 return;
2562 }
2563 if (VDBG || (DBG && nri.request.isRequest())) {
2564 log("releasing " + nri.request + " (timeout)");
2565 }
2566 handleRemoveNetworkRequest(nri);
2567 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002568 }
2569
Erik Klineacdd6392016-07-07 16:50:58 +09002570 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002571 final NetworkRequestInfo nri =
2572 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2573 if (nri == null) {
2574 return;
Erik Kline57faba92015-11-25 12:49:38 +09002575 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002576 if (VDBG || (DBG && nri.request.isRequest())) {
2577 log("releasing " + nri.request + " (release request)");
2578 }
2579 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002580 }
Erik Klineacdd6392016-07-07 16:50:58 +09002581
Hugo Benichidba33db2017-03-23 22:40:44 +09002582 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002583 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002584 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002585
Erik Klineacdd6392016-07-07 16:50:58 +09002586 synchronized (mUidToNetworkRequestCount) {
2587 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2588 if (requests < 1) {
2589 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2590 nri.mUid);
2591 } else if (requests == 1) {
2592 mUidToNetworkRequestCount.removeAt(
2593 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2594 } else {
2595 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2596 }
2597 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002598
Erik Klineacdd6392016-07-07 16:50:58 +09002599 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2600 if (nri.request.isRequest()) {
2601 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002602 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002603 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002604 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002605 nai.removeRequest(nri.request.requestId);
2606 if (VDBG) {
2607 log(" Removing from current network " + nai.name() +
2608 ", leaving " + nai.numNetworkRequests() + " requests.");
2609 }
2610 // If there are still lingered requests on this network, don't tear it down,
2611 // but resume lingering instead.
2612 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002613 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002614 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2615 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002616 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002617 wasKept = true;
2618 }
Hugo Benichicd952782017-09-20 11:20:14 +09002619 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002620 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2621 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002622 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002623 }
Erik Klineacdd6392016-07-07 16:50:58 +09002624 }
2625
2626 // TODO: remove this code once we know that the Slog.wtf is never hit.
2627 //
2628 // Find all networks that are satisfying this request and remove the request
2629 // from their request lists.
2630 // TODO - it's my understanding that for a request there is only a single
2631 // network satisfying it, so this loop is wasteful
2632 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2633 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2634 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2635 otherNai.name() + ", but mNetworkAgentInfos says " +
2636 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002637 }
2638 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002639
Erik Klineacdd6392016-07-07 16:50:58 +09002640 // Maintain the illusion. When this request arrived, we might have pretended
2641 // that a network connected to serve it, even though the network was already
2642 // connected. Now that this request has gone away, we might have to pretend
2643 // that the network disconnected. LegacyTypeTracker will generate that
2644 // phantom disconnect for this type.
2645 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2646 boolean doRemove = true;
2647 if (wasKept) {
2648 // check if any of the remaining requests for this network are for the
2649 // same legacy type - if so, don't remove the nai
2650 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2651 NetworkRequest otherRequest = nai.requestAt(i);
2652 if (otherRequest.legacyType == nri.request.legacyType &&
2653 otherRequest.isRequest()) {
2654 if (DBG) log(" still have other legacy request - leaving");
2655 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002656 }
2657 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002658 }
2659
Erik Klineacdd6392016-07-07 16:50:58 +09002660 if (doRemove) {
2661 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002662 }
2663 }
Erik Klineacdd6392016-07-07 16:50:58 +09002664
2665 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2666 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2667 nri.request);
2668 }
2669 } else {
2670 // listens don't have a singular affectedNetwork. Check all networks to see
2671 // if this listen request applies and remove it.
2672 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2673 nai.removeRequest(nri.request.requestId);
2674 if (nri.request.networkCapabilities.hasSignalStrength() &&
2675 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2676 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2677 }
2678 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002679 }
2680 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002681
Lorenzo Colitti18660282016-07-04 12:55:44 +09002682 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2684 enforceConnectivityInternalPermission();
2685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002686 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002687 }
2688
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002689 @Override
2690 public void setAvoidUnvalidated(Network network) {
2691 enforceConnectivityInternalPermission();
2692 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2693 }
2694
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002695 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2696 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2697 " accept=" + accept + " always=" + always);
2698
2699 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2700 if (nai == null) {
2701 // Nothing to do.
2702 return;
2703 }
2704
2705 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002706 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002707 return;
2708 }
2709
2710 if (!nai.networkMisc.explicitlySelected) {
2711 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2712 }
2713
2714 if (accept != nai.networkMisc.acceptUnvalidated) {
2715 int oldScore = nai.getCurrentScore();
2716 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002717 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 sendUpdatedScoreToFactories(nai);
2719 }
2720
2721 if (always) {
2722 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002723 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 }
2725
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002726 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002727 // Tell the NetworkAgent to not automatically reconnect to the network.
2728 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2729 // Teardown the nework.
2730 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002731 }
2732
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002733 }
2734
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002735 private void handleSetAvoidUnvalidated(Network network) {
2736 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2737 if (nai == null || nai.lastValidated) {
2738 // Nothing to do. The network either disconnected or revalidated.
2739 return;
2740 }
2741 if (!nai.avoidUnvalidated) {
2742 int oldScore = nai.getCurrentScore();
2743 nai.avoidUnvalidated = true;
2744 rematchAllNetworksAndRequests(nai, oldScore);
2745 sendUpdatedScoreToFactories(nai);
2746 }
2747 }
2748
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002749 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002750 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002751 mHandler.sendMessageDelayed(
2752 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2753 PROMPT_UNVALIDATED_DELAY_MS);
2754 }
2755
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002756 @Override
2757 public void startCaptivePortalApp(Network network) {
2758 enforceConnectivityInternalPermission();
2759 mHandler.post(() -> {
2760 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2761 if (nai == null) return;
2762 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2763 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2764 });
2765 }
2766
Hugo Benichic8e9e122016-09-14 23:23:08 +00002767 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002768 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002769 }
2770
Erik Kline065ab6e2016-10-02 18:02:14 +09002771 private void rematchForAvoidBadWifiUpdate() {
2772 rematchAllNetworksAndRequests(null, 0);
2773 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2774 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2775 sendUpdatedScoreToFactories(nai);
2776 }
2777 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002778 }
2779
Erik Kline065ab6e2016-10-02 18:02:14 +09002780 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002781 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002782 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002783 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002784 if (!configRestrict) {
2785 pw.println("Bad Wi-Fi avoidance: unrestricted");
2786 return;
2787 }
2788
2789 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2790 pw.increaseIndent();
2791 pw.println("Config restrict: " + configRestrict);
2792
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002793 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002794 String description;
2795 // Can't use a switch statement because strings are legal case labels, but null is not.
2796 if ("0".equals(value)) {
2797 description = "get stuck";
2798 } else if (value == null) {
2799 description = "prompt";
2800 } else if ("1".equals(value)) {
2801 description = "avoid";
2802 } else {
2803 description = value + " (?)";
2804 }
2805 pw.println("User setting: " + description);
2806 pw.println("Network overrides:");
2807 pw.increaseIndent();
2808 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2809 if (nai.avoidUnvalidated) {
2810 pw.println(nai.name());
2811 }
2812 }
2813 pw.decreaseIndent();
2814 pw.decreaseIndent();
2815 }
2816
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002817 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2818 final String action;
2819 switch (type) {
2820 case NO_INTERNET:
2821 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2822 break;
2823 case LOST_INTERNET:
2824 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2825 break;
2826 default:
2827 Slog.wtf(TAG, "Unknown notification type " + type);
2828 return;
2829 }
2830
2831 Intent intent = new Intent(action);
2832 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2833 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2834 intent.setClassName("com.android.settings",
2835 "com.android.settings.wifi.WifiNoInternetDialog");
2836
2837 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2838 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2839 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2840 }
2841
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002842 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002843 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002844 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2845
2846 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2847 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002848 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002849 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002850 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2851 return;
2852 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002853 showValidationNotification(nai, NotificationType.NO_INTERNET);
2854 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002855
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002856 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2857 NetworkCapabilities nc = nai.networkCapabilities;
2858 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002859
Erik Kline065ab6e2016-10-02 18:02:14 +09002860 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002861 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002862 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2863 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002864 }
2865
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002866 @Override
2867 public int getMultipathPreference(Network network) {
2868 enforceAccessPermission();
2869
2870 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002871 if (nai != null && nai.networkCapabilities
2872 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002873 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2874 }
2875
2876 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2877 }
2878
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002879 private class InternalHandler extends Handler {
2880 public InternalHandler(Looper looper) {
2881 super(looper);
2882 }
2883
2884 @Override
2885 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002886 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002887 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002888 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002889 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002890 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002891 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002892 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002894 break;
2895 }
Jason Monkdecd2952013-10-10 14:02:51 -04002896 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002897 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002898 break;
2899 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002900 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002901 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2902 break;
2903 }
2904 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2905 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002906 break;
2907 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002908 case EVENT_REGISTER_NETWORK_AGENT: {
2909 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2910 break;
2911 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002912 case EVENT_REGISTER_NETWORK_REQUEST:
2913 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002914 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002915 break;
2916 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002917 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2918 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002919 handleRegisterNetworkRequestWithIntent(msg);
2920 break;
2921 }
Erik Kline57faba92015-11-25 12:49:38 +09002922 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2923 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2924 handleTimedOutNetworkRequest(nri);
2925 break;
2926 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002927 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2928 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2929 break;
2930 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002931 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002932 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002933 break;
2934 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002935 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002936 Network network = (Network) msg.obj;
2937 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002938 break;
2939 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002940 case EVENT_SET_AVOID_UNVALIDATED: {
2941 handleSetAvoidUnvalidated((Network) msg.obj);
2942 break;
2943 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002944 case EVENT_PROMPT_UNVALIDATED: {
2945 handlePromptUnvalidated((Network) msg.obj);
2946 break;
2947 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002948 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2949 handleMobileDataAlwaysOn();
2950 break;
2951 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002952 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2953 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2954 mKeepaliveTracker.handleStartKeepalive(msg);
2955 break;
2956 }
2957 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2958 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2959 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2960 int slot = msg.arg1;
2961 int reason = msg.arg2;
2962 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2963 break;
2964 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002965 case EVENT_SYSTEM_READY: {
2966 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2967 nai.networkMonitor.systemReady = true;
2968 }
2969 break;
2970 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002971 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002972 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002973 break;
2974 }
Erik Klinea24d4592018-01-11 21:07:29 +09002975 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2976 handlePrivateDnsSettingsChanged();
2977 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
2979 }
2980 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002981
2982 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002983 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002984 public int tether(String iface, String callerPkg) {
2985 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002986 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002987 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002988 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002989 } else {
2990 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2991 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002992 }
2993
2994 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002995 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002996 public int untether(String iface, String callerPkg) {
2997 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002998
2999 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003000 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003001 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003002 } else {
3003 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3004 }
3005 }
3006
3007 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003009 public int getLastTetherError(String iface) {
3010 enforceTetherAccessPermission();
3011
3012 if (isTetheringSupported()) {
3013 return mTethering.getLastTetherError(iface);
3014 } else {
3015 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3016 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 }
3018
3019 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003020 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003021 public String[] getTetherableUsbRegexs() {
3022 enforceTetherAccessPermission();
3023 if (isTetheringSupported()) {
3024 return mTethering.getTetherableUsbRegexs();
3025 } else {
3026 return new String[0];
3027 }
3028 }
3029
Lorenzo Colitti18660282016-07-04 12:55:44 +09003030 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003031 public String[] getTetherableWifiRegexs() {
3032 enforceTetherAccessPermission();
3033 if (isTetheringSupported()) {
3034 return mTethering.getTetherableWifiRegexs();
3035 } else {
3036 return new String[0];
3037 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003038 }
3039
Lorenzo Colitti18660282016-07-04 12:55:44 +09003040 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003041 public String[] getTetherableBluetoothRegexs() {
3042 enforceTetherAccessPermission();
3043 if (isTetheringSupported()) {
3044 return mTethering.getTetherableBluetoothRegexs();
3045 } else {
3046 return new String[0];
3047 }
3048 }
3049
Lorenzo Colitti18660282016-07-04 12:55:44 +09003050 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003051 public int setUsbTethering(boolean enable, String callerPkg) {
3052 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003053 if (isTetheringSupported()) {
3054 return mTethering.setUsbTethering(enable);
3055 } else {
3056 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3057 }
3058 }
3059
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003060 // TODO - move iface listing, queries, etc to new module
3061 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003062 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003063 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003064 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003065 return mTethering.getTetherableIfaces();
3066 }
3067
Lorenzo Colitti18660282016-07-04 12:55:44 +09003068 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003069 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003070 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003071 return mTethering.getTetheredIfaces();
3072 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003073
Lorenzo Colitti18660282016-07-04 12:55:44 +09003074 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003075 public String[] getTetheringErroredIfaces() {
3076 enforceTetherAccessPermission();
3077 return mTethering.getErroredIfaces();
3078 }
3079
Lorenzo Colitti18660282016-07-04 12:55:44 +09003080 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003081 public String[] getTetheredDhcpRanges() {
3082 enforceConnectivityInternalPermission();
3083 return mTethering.getTetheredDhcpRanges();
3084 }
3085
Udam Sainic3b640c2017-06-07 12:06:28 -07003086 @Override
3087 public boolean isTetheringSupported(String callerPkg) {
3088 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3089 return isTetheringSupported();
3090 }
3091
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003092 // if ro.tether.denied = true we default to no tethering
3093 // gservices could set the secure setting to 1 though to enable it on a build where it
3094 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003095 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003096 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3097 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3098 Settings.Global.TETHER_SUPPORTED, defaultVal));
3099 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003100 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003101
3102 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3103 boolean adminUser = false;
3104 final long token = Binder.clearCallingIdentity();
3105 try {
3106 adminUser = mUserManager.isAdminUser();
3107 } finally {
3108 Binder.restoreCallingIdentity(token);
3109 }
3110
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003111 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003112 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003113
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003114 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003115 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3116 String callerPkg) {
3117 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003118 if (!isTetheringSupported()) {
3119 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3120 return;
3121 }
3122 mTethering.startTethering(type, receiver, showProvisioningUi);
3123 }
3124
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003125 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003126 public void stopTethering(int type, String callerPkg) {
3127 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003128 mTethering.stopTethering(type);
3129 }
3130
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003131 // Called when we lose the default network and have no replacement yet.
3132 // This will automatically be cleared after X seconds or a new default network
3133 // becomes CONNECTED, whichever happens first. The timer is started by the
3134 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003135 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003136 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003137 if (mNetTransitionWakeLock.isHeld()) {
3138 return;
3139 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003140 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003141 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3142 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003143 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003144 mWakelockLogs.log("ACQUIRE for " + forWhom);
3145 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3146 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003147 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003148
Hugo Benichi4c31b342017-03-30 23:18:10 +09003149 // Called when we gain a new default network to release the network transition wakelock in a
3150 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3151 // message is cancelled.
3152 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003153 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003154 if (!mNetTransitionWakeLock.isHeld()) {
3155 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003156 }
3157 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003158 // Cancel self timeout on wakelock hold.
3159 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3160 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3161 mHandler.sendMessageDelayed(msg, 1000);
3162 }
3163
3164 // Called when either message of ensureNetworkTransitionWakelock or
3165 // scheduleReleaseNetworkTransitionWakelock is processed.
3166 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3167 String event = eventName(eventId);
3168 synchronized (this) {
3169 if (!mNetTransitionWakeLock.isHeld()) {
3170 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3171 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3172 return;
3173 }
3174 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003175 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3176 mTotalWakelockDurationMs += lockDuration;
3177 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3178 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003179 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003180 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003181 }
3182
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003183 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003184 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003185 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003186 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003187 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003188 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003189 }
3190
Lorenzo Colitti18660282016-07-04 12:55:44 +09003191 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003192 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003193 enforceAccessPermission();
3194 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003195 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003196 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003197 mHandler.sendMessage(
3198 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3199 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003200
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003201 private void handleReportNetworkConnectivity(
3202 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003203 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003204 if (network == null) {
3205 nai = getDefaultNetwork();
3206 } else {
3207 nai = getNetworkAgentInfoForNetwork(network);
3208 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003209 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3210 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3211 return;
3212 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003213 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003214 if (hasConnectivity == nai.lastValidated) {
3215 return;
3216 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003217 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003218 int netid = nai.network.netId;
3219 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003220 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003221 // Validating a network that has not yet connected could result in a call to
3222 // rematchNetworkAndRequests() which is not meant to work on such networks.
3223 if (!nai.everConnected) {
3224 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003225 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003226 LinkProperties lp = getLinkProperties(nai);
3227 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3228 return;
3229 }
3230 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003231 }
3232
Paul Jensencee9b512015-05-06 07:32:40 -04003233 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003234 // this information is already available as a world read/writable jvm property
3235 // so this API change wouldn't have a benifit. It also breaks the passing
3236 // of proxy info to all the JVMs.
3237 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003238 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003239 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003240 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3241 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003242 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003243 }
3244
Lorenzo Colitti18660282016-07-04 12:55:44 +09003245 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003246 public ProxyInfo getProxyForNetwork(Network network) {
3247 if (network == null) return getDefaultProxy();
3248 final ProxyInfo globalProxy = getGlobalProxy();
3249 if (globalProxy != null) return globalProxy;
3250 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3251 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3252 // caller may not have.
3253 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3254 if (nai == null) return null;
3255 synchronized (nai) {
3256 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3257 if (proxyInfo == null) return null;
3258 return new ProxyInfo(proxyInfo);
3259 }
3260 }
3261
Paul Jensene0bef712014-12-10 15:12:18 -05003262 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3263 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3264 // proxy is null then there is no proxy in place).
3265 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3266 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3267 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3268 proxy = null;
3269 }
3270 return proxy;
3271 }
3272
3273 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3274 // better for determining if a new proxy broadcast is necessary:
3275 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3276 // avoid unnecessary broadcasts.
3277 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3278 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3279 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3280 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3281 // all set.
3282 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3283 a = canonicalizeProxyInfo(a);
3284 b = canonicalizeProxyInfo(b);
3285 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3286 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3287 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3288 }
3289
Jason Monk207900c2014-04-25 15:00:09 -04003290 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003291 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003292
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003293 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 if (proxyProperties == mGlobalProxy) return;
3295 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3296 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3297
3298 String host = "";
3299 int port = 0;
3300 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003301 String pacFileUrl = "";
3302 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003303 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003304 if (!proxyProperties.isValid()) {
3305 if (DBG)
3306 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3307 return;
3308 }
Jason Monk207900c2014-04-25 15:00:09 -04003309 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310 host = mGlobalProxy.getHost();
3311 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003312 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003313 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003314 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 } else {
3317 mGlobalProxy = null;
3318 }
3319 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003320 final long token = Binder.clearCallingIdentity();
3321 try {
3322 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3323 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3324 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3325 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003326 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003327 } finally {
3328 Binder.restoreCallingIdentity(token);
3329 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330
Jason Monkcf0f97a2014-10-02 15:39:38 -04003331 if (mGlobalProxy == null) {
3332 proxyProperties = mDefaultProxy;
3333 }
3334 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003336 }
3337
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003338 private void loadGlobalProxy() {
3339 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003340 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3341 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3342 String exclList = Settings.Global.getString(res,
3343 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003344 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3345 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003346 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003347 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003348 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003349 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003350 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003351 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003352 if (!proxyProperties.isValid()) {
3353 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3354 return;
3355 }
3356
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003357 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003358 mGlobalProxy = proxyProperties;
3359 }
3360 }
3361 }
3362
Jason Monk207900c2014-04-25 15:00:09 -04003363 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003364 // this information is already available as a world read/writable jvm property
3365 // so this API change wouldn't have a benifit. It also breaks the passing
3366 // of proxy info to all the JVMs.
3367 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003368 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003369 return mGlobalProxy;
3370 }
3371 }
3372
Jason Monk207900c2014-04-25 15:00:09 -04003373 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003374 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003375 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003376 proxy = null;
3377 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003378 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003379 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003380 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003381 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003382 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3383 return;
3384 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003385
3386 // This call could be coming from the PacManager, containing the port of the local
3387 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3388 // global (to get the correct local port), and send a broadcast.
3389 // TODO: Switch PacManager to have its own message to send back rather than
3390 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003391 if ((mGlobalProxy != null) && (proxy != null)
3392 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003393 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3394 mGlobalProxy = proxy;
3395 sendProxyBroadcast(mGlobalProxy);
3396 return;
3397 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003398 mDefaultProxy = proxy;
3399
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003400 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003401 if (!mDefaultProxyDisabled) {
3402 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 }
3404 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003405 }
3406
Paul Jensene0bef712014-12-10 15:12:18 -05003407 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3408 // This method gets called when any network changes proxy, but the broadcast only ever contains
3409 // the default proxy (even if it hasn't changed).
3410 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3411 // world where an app might be bound to a non-default network.
3412 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3413 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3414 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3415
3416 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3417 sendProxyBroadcast(getDefaultProxy());
3418 }
3419 }
3420
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003422 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3423 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003424 if (!TextUtils.isEmpty(proxy)) {
3425 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003426 if (data.length == 0) {
3427 return;
3428 }
3429
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 String proxyHost = data[0];
3431 int proxyPort = 8080;
3432 if (data.length > 1) {
3433 try {
3434 proxyPort = Integer.parseInt(data[1]);
3435 } catch (NumberFormatException e) {
3436 return;
3437 }
3438 }
Jason Monk207900c2014-04-25 15:00:09 -04003439 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003440 setGlobalProxy(p);
3441 }
3442 }
3443
Jason Monk207900c2014-04-25 15:00:09 -04003444 private void sendProxyBroadcast(ProxyInfo proxy) {
3445 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003446 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003447 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003448 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003449 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3450 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003451 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003452 final long ident = Binder.clearCallingIdentity();
3453 try {
3454 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3455 } finally {
3456 Binder.restoreCallingIdentity(ident);
3457 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003458 }
3459
3460 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003461 final private HashMap<Uri, Integer> mUriEventMap;
3462 final private Context mContext;
3463 final private Handler mHandler;
3464
3465 SettingsObserver(Context context, Handler handler) {
3466 super(null);
3467 mUriEventMap = new HashMap<Uri, Integer>();
3468 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003470 }
3471
Erik Klineda4bfa82015-04-30 12:58:40 +09003472 void observe(Uri uri, int what) {
3473 mUriEventMap.put(uri, what);
3474 final ContentResolver resolver = mContext.getContentResolver();
3475 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003476 }
3477
3478 @Override
3479 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003480 Slog.wtf(TAG, "Should never be reached.");
3481 }
3482
3483 @Override
3484 public void onChange(boolean selfChange, Uri uri) {
3485 final Integer what = mUriEventMap.get(uri);
3486 if (what != null) {
3487 mHandler.obtainMessage(what.intValue()).sendToTarget();
3488 } else {
3489 loge("No matching event to send for URI=" + uri);
3490 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003491 }
3492 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003493
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003494 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003495 Slog.d(TAG, s);
3496 }
3497
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003498 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003499 Slog.e(TAG, s);
3500 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003501
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003502 private static void loge(String s, Throwable t) {
3503 Slog.e(TAG, s, t);
3504 }
3505
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003506 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003507 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003508 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3509 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3510 *
3511 * @param oldPackage Package name of the application which currently controls VPN, which will
3512 * be replaced. If there is no such application, this should should either be
3513 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3514 * @param newPackage Package name of the application which should gain control of VPN, or
3515 * {@code null} to disable.
3516 * @param userId User for whom to prepare the new VPN.
3517 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003518 * @hide
3519 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003520 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003521 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3522 int userId) {
3523 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003524
Hugo Benichi20035e02017-04-26 14:53:28 +09003525 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003526 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003527 Vpn vpn = mVpns.get(userId);
3528 if (vpn != null) {
3529 return vpn.prepare(oldPackage, newPackage);
3530 } else {
3531 return false;
3532 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003533 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003534 }
3535
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003536 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003537 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3538 * This method is used by system-privileged apps.
3539 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3540 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3541 *
3542 * @param packageName The package for which authorization state should change.
3543 * @param userId User for whom {@code packageName} is installed.
3544 * @param authorized {@code true} if this app should be able to start a VPN connection without
3545 * explicit user approval, {@code false} if not.
3546 *
Jeff Davidson05542602014-08-11 14:07:27 -07003547 * @hide
3548 */
3549 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003550 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3551 enforceCrossUserPermission(userId);
3552
Hugo Benichi20035e02017-04-26 14:53:28 +09003553 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003554 Vpn vpn = mVpns.get(userId);
3555 if (vpn != null) {
3556 vpn.setPackageAuthorization(packageName, authorized);
3557 }
Jeff Davidson05542602014-08-11 14:07:27 -07003558 }
3559 }
3560
3561 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003562 * Configure a TUN interface and return its file descriptor. Parameters
3563 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003564 * and not available in ConnectivityManager. Permissions are checked in
3565 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003566 * @hide
3567 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003568 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003569 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003570 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003571 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003572 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003573 return mVpns.get(user).establish(config);
3574 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003575 }
3576
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003577 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003578 * Start legacy VPN, controlling native daemons as needed. Creates a
3579 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003580 */
3581 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003582 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003583 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003584 final LinkProperties egress = getActiveLinkProperties();
3585 if (egress == null) {
3586 throw new IllegalStateException("Missing active network connection");
3587 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003588 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003589 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003590 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3591 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003592 }
3593
3594 /**
3595 * Return the information of the ongoing legacy VPN. This method is used
3596 * by VpnSettings and not available in ConnectivityManager. Permissions
3597 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003598 */
3599 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003600 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3601 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003602
Hugo Benichi20035e02017-04-26 14:53:28 +09003603 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003604 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003605 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003606 }
3607
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003608 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003609 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3610 * and not available in ConnectivityManager.
3611 */
3612 @Override
3613 public VpnInfo[] getAllVpnInfo() {
3614 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003615 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003616 if (mLockdownEnabled) {
3617 return new VpnInfo[0];
3618 }
3619
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003620 List<VpnInfo> infoList = new ArrayList<>();
3621 for (int i = 0; i < mVpns.size(); i++) {
3622 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3623 if (info != null) {
3624 infoList.add(info);
3625 }
3626 }
3627 return infoList.toArray(new VpnInfo[infoList.size()]);
3628 }
3629 }
3630
3631 /**
3632 * @return VPN information for accounting, or null if we can't retrieve all required
3633 * information, e.g primary underlying iface.
3634 */
3635 @Nullable
3636 private VpnInfo createVpnInfo(Vpn vpn) {
3637 VpnInfo info = vpn.getVpnInfo();
3638 if (info == null) {
3639 return null;
3640 }
3641 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3642 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3643 // the underlyingNetworks list.
3644 if (underlyingNetworks == null) {
3645 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3646 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3647 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3648 }
3649 } else if (underlyingNetworks.length > 0) {
3650 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3651 if (linkProperties != null) {
3652 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3653 }
3654 }
3655 return info.primaryUnderlyingIface == null ? null : info;
3656 }
3657
3658 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003659 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3660 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003661 * Permissions are checked in Vpn class.
3662 * @hide
3663 */
3664 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003665 public VpnConfig getVpnConfig(int userId) {
3666 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003667 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003668 Vpn vpn = mVpns.get(userId);
3669 if (vpn != null) {
3670 return vpn.getVpnConfig();
3671 } else {
3672 return null;
3673 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003674 }
3675 }
3676
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003677 @Override
3678 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003679 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3680 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3681 return false;
3682 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003683
Hugo Benichi69744342017-11-27 10:57:16 +09003684 synchronized (mVpns) {
3685 // Tear down existing lockdown if profile was removed
3686 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3687 if (mLockdownEnabled) {
3688 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3689 if (profileTag == null) {
3690 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3691 return false;
3692 }
3693 String profileName = new String(profileTag);
3694 final VpnProfile profile = VpnProfile.decode(
3695 profileName, mKeyStore.get(Credentials.VPN + profileName));
3696 if (profile == null) {
3697 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3698 setLockdownTracker(null);
3699 return true;
3700 }
3701 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003702 Vpn vpn = mVpns.get(user);
3703 if (vpn == null) {
3704 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3705 return false;
3706 }
3707 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003708 } else {
3709 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003710 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003711 }
3712
3713 return true;
3714 }
3715
3716 /**
3717 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3718 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3719 */
Hugo Benichi69744342017-11-27 10:57:16 +09003720 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003721 private void setLockdownTracker(LockdownVpnTracker tracker) {
3722 // Shutdown any existing tracker
3723 final LockdownVpnTracker existing = mLockdownTracker;
3724 mLockdownTracker = null;
3725 if (existing != null) {
3726 existing.shutdown();
3727 }
3728
Robin Leec3736bc2017-03-10 16:19:54 +00003729 if (tracker != null) {
3730 mLockdownTracker = tracker;
3731 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003732 }
3733 }
3734
Hugo Benichi69744342017-11-27 10:57:16 +09003735 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003736 private void throwIfLockdownEnabled() {
3737 if (mLockdownEnabled) {
3738 throw new IllegalStateException("Unavailable in lockdown mode");
3739 }
3740 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003741
Robin Lee244ce8e2016-01-05 18:03:46 +00003742 /**
Robin Lee17e61832016-05-09 13:46:28 +01003743 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3744 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003745 *
Robin Lee17e61832016-05-09 13:46:28 +01003746 * @return {@code true} if the service was started, the service was already connected, or there
3747 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003748 */
Robin Lee17e61832016-05-09 13:46:28 +01003749 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003750 synchronized (mVpns) {
3751 Vpn vpn = mVpns.get(userId);
3752 if (vpn == null) {
3753 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3754 // exists already.
3755 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3756 return false;
3757 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003758
Robin Lee812800c2016-05-13 15:38:08 +01003759 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003760 }
3761 }
3762
3763 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003764 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3765 enforceSettingsPermission();
3766 enforceCrossUserPermission(userId);
3767
3768 synchronized (mVpns) {
3769 Vpn vpn = mVpns.get(userId);
3770 if (vpn == null) {
3771 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3772 return false;
3773 }
3774 return vpn.isAlwaysOnPackageSupported(packageName);
3775 }
3776 }
3777
3778 @Override
Robin Leedc679712016-05-03 13:23:03 +01003779 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003780 enforceConnectivityInternalPermission();
3781 enforceCrossUserPermission(userId);
3782
Robin Lee244ce8e2016-01-05 18:03:46 +00003783 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003784 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3785 if (LockdownVpnTracker.isEnabled()) {
3786 return false;
3787 }
3788
Robin Lee244ce8e2016-01-05 18:03:46 +00003789 Vpn vpn = mVpns.get(userId);
3790 if (vpn == null) {
3791 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3792 return false;
3793 }
Robin Lee17e61832016-05-09 13:46:28 +01003794 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003795 return false;
3796 }
Robin Lee17e61832016-05-09 13:46:28 +01003797 if (!startAlwaysOnVpn(userId)) {
3798 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003799 return false;
3800 }
3801 }
3802 return true;
3803 }
3804
3805 @Override
3806 public String getAlwaysOnVpnPackage(int userId) {
3807 enforceConnectivityInternalPermission();
3808 enforceCrossUserPermission(userId);
3809
3810 synchronized (mVpns) {
3811 Vpn vpn = mVpns.get(userId);
3812 if (vpn == null) {
3813 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3814 return null;
3815 }
3816 return vpn.getAlwaysOnPackage();
3817 }
3818 }
3819
Wink Savilleab9321d2013-06-29 21:10:57 -07003820 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003821 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003822 // TODO: Remove? Any reason to trigger a provisioning check?
3823 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003824 }
3825
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003826 /** Location to an updatable file listing carrier provisioning urls.
3827 * An example:
3828 *
3829 * <?xml version="1.0" encoding="utf-8"?>
3830 * <provisioningUrls>
3831 * <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 -07003832 * </provisioningUrls>
3833 */
3834 private static final String PROVISIONING_URL_PATH =
3835 "/data/misc/radio/provisioning_urls.xml";
3836 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003837
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003838 /** XML tag for root element. */
3839 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3840 /** XML tag for individual url */
3841 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003842 /** XML attribute for mcc */
3843 private static final String ATTR_MCC = "mcc";
3844 /** XML attribute for mnc */
3845 private static final String ATTR_MNC = "mnc";
3846
Paul Jensen434dde82015-06-11 09:43:30 -04003847 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003848 FileReader fileReader = null;
3849 XmlPullParser parser = null;
3850 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003851
3852 try {
3853 fileReader = new FileReader(mProvisioningUrlFile);
3854 parser = Xml.newPullParser();
3855 parser.setInput(fileReader);
3856 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3857
3858 while (true) {
3859 XmlUtils.nextElement(parser);
3860
3861 String element = parser.getName();
3862 if (element == null) break;
3863
Paul Jensen434dde82015-06-11 09:43:30 -04003864 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003865 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3866 try {
3867 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3868 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3869 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3870 parser.next();
3871 if (parser.getEventType() == XmlPullParser.TEXT) {
3872 return parser.getText();
3873 }
3874 }
3875 }
3876 } catch (NumberFormatException e) {
3877 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3878 }
3879 }
3880 }
3881 return null;
3882 } catch (FileNotFoundException e) {
3883 loge("Carrier Provisioning Urls file not found");
3884 } catch (XmlPullParserException e) {
3885 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3886 } catch (IOException e) {
3887 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3888 } finally {
3889 if (fileReader != null) {
3890 try {
3891 fileReader.close();
3892 } catch (IOException e) {}
3893 }
3894 }
3895 return null;
3896 }
3897
Wink Saville42d4f082013-07-20 20:31:59 -07003898 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003899 public String getMobileProvisioningUrl() {
3900 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003901 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003902 if (TextUtils.isEmpty(url)) {
3903 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003904 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003905 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003906 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003907 }
Wink Saville8cf35602013-07-10 23:00:07 -07003908 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003909 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003910 String phoneNumber = mTelephonyManager.getLine1Number();
3911 if (TextUtils.isEmpty(phoneNumber)) {
3912 phoneNumber = "0000000000";
3913 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003914 url = String.format(url,
3915 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3916 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003917 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003918 }
3919
Wink Savilleab9321d2013-06-29 21:10:57 -07003920 return url;
3921 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003922
Wink Saville948282b2013-08-29 08:55:16 -07003923 @Override
3924 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003925 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003926 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003927 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3928 return;
3929 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003930 final long ident = Binder.clearCallingIdentity();
3931 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003932 // Concatenate the range of types onto the range of NetIDs.
3933 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3934 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003935 } finally {
3936 Binder.restoreCallingIdentity(ident);
3937 }
Wink Saville948282b2013-08-29 08:55:16 -07003938 }
Wink Saville7788c612013-08-29 14:57:08 -07003939
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003940 @Override
3941 public void setAirplaneMode(boolean enable) {
3942 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003943 final long ident = Binder.clearCallingIdentity();
3944 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003945 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003946 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003947 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3948 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003949 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003950 } finally {
3951 Binder.restoreCallingIdentity(ident);
3952 }
3953 }
3954
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003955 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003956 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003957 Vpn userVpn = mVpns.get(userId);
3958 if (userVpn != null) {
3959 loge("Starting user already has a VPN");
3960 return;
3961 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003962 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003963 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003964 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3965 updateLockdownVpn();
3966 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003967 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 }
3969
3970 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003971 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003972 Vpn userVpn = mVpns.get(userId);
3973 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003974 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003975 return;
3976 }
Robin Lee17e61832016-05-09 13:46:28 +01003977 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003978 mVpns.delete(userId);
3979 }
3980 }
3981
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003982 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003983 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003984 final int vpnsSize = mVpns.size();
3985 for (int i = 0; i < vpnsSize; i++) {
3986 Vpn vpn = mVpns.valueAt(i);
3987 vpn.onUserAdded(userId);
3988 }
3989 }
3990 }
3991
3992 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003993 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003994 final int vpnsSize = mVpns.size();
3995 for (int i = 0; i < vpnsSize; i++) {
3996 Vpn vpn = mVpns.valueAt(i);
3997 vpn.onUserRemoved(userId);
3998 }
3999 }
4000 }
4001
Robin Lee89e7a692016-02-29 14:38:17 +00004002 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004003 synchronized (mVpns) {
4004 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4005 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4006 updateLockdownVpn();
4007 } else {
4008 startAlwaysOnVpn(userId);
4009 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004010 }
4011 }
4012
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004013 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4014 @Override
4015 public void onReceive(Context context, Intent intent) {
4016 final String action = intent.getAction();
4017 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4018 if (userId == UserHandle.USER_NULL) return;
4019
Robin Lee323f29d2016-05-04 16:38:06 +01004020 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004021 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004022 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004023 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004024 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4025 onUserAdded(userId);
4026 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4027 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004028 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4029 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004030 }
4031 }
4032 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004033
Robin Lee95204e02017-01-27 11:59:22 +00004034 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4035 @Override
4036 public void onReceive(Context context, Intent intent) {
4037 // Try creating lockdown tracker, since user present usually means
4038 // unlocked keystore.
4039 updateLockdownVpn();
4040 mContext.unregisterReceiver(this);
4041 }
4042 };
4043
Robert Greenwalta67be032014-05-16 15:49:14 -07004044 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4045 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004046 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4047 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004048
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004049 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4050 // Map from UID to number of NetworkRequests that UID has filed.
4051 @GuardedBy("mUidToNetworkRequestCount")
4052 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4053
Robert Greenwalta67be032014-05-16 15:49:14 -07004054 private static class NetworkFactoryInfo {
4055 public final String name;
4056 public final Messenger messenger;
4057 public final AsyncChannel asyncChannel;
4058
4059 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4060 this.name = name;
4061 this.messenger = messenger;
4062 this.asyncChannel = asyncChannel;
4063 }
4064 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004066 private void ensureNetworkRequestHasType(NetworkRequest request) {
4067 if (request.type == NetworkRequest.Type.NONE) {
4068 throw new IllegalArgumentException(
4069 "All NetworkRequests in ConnectivityService must have a type");
4070 }
4071 }
4072
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004073 /**
4074 * Tracks info about the requester.
4075 * Also used to notice when the calling process dies so we can self-expire
4076 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004077 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004079 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004080 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004081 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 final int mPid;
4083 final int mUid;
4084 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004086 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004088 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004089 mPendingIntent = pi;
4090 messenger = null;
4091 mBinder = null;
4092 mPid = getCallingPid();
4093 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004094 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095 }
4096
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004097 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098 super();
4099 messenger = m;
4100 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004101 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 mBinder = binder;
4103 mPid = getCallingPid();
4104 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004105 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004106 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107
4108 try {
4109 mBinder.linkToDeath(this, 0);
4110 } catch (RemoteException e) {
4111 binderDied();
4112 }
4113 }
4114
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004115 private void enforceRequestCountLimit() {
4116 synchronized (mUidToNetworkRequestCount) {
4117 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4118 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004119 throw new ServiceSpecificException(
4120 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004121 }
4122 mUidToNetworkRequestCount.put(mUid, networkRequests);
4123 }
4124 }
4125
Robert Greenwalt9258c642014-03-26 16:47:06 -07004126 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004127 if (mBinder != null) {
4128 mBinder.unlinkToDeath(this, 0);
4129 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004130 }
4131
4132 public void binderDied() {
4133 log("ConnectivityService NetworkRequestInfo binderDied(" +
4134 request + ", " + mBinder + ")");
4135 releaseNetworkRequest(request);
4136 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004137
4138 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004139 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004140 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004141 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 }
4143
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004144 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4145 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4146 if (badCapability != null) {
4147 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004148 }
4149 }
4150
Erik Kline9d598e12015-07-13 16:37:51 +09004151 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004152 final SortedSet<Integer> thresholds = new TreeSet();
4153 synchronized (nai) {
4154 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4155 if (nri.request.networkCapabilities.hasSignalStrength() &&
4156 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4157 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4158 }
4159 }
4160 }
Erik Kline9d598e12015-07-13 16:37:51 +09004161 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004162 }
4163
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004164 private void updateSignalStrengthThresholds(
4165 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4166 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004167 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004168 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4169
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004170 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004171 String detail;
4172 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4173 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4174 } else {
4175 detail = reason;
4176 }
4177 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4178 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4179 }
4180
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004181 nai.asyncChannel.sendMessage(
4182 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004183 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004184 }
4185
Etan Cohen859748f2017-04-03 17:42:34 -07004186 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4187 if (nc == null) {
4188 return;
4189 }
4190 NetworkSpecifier ns = nc.getNetworkSpecifier();
4191 if (ns == null) {
4192 return;
4193 }
4194 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4195 ns.assertValidFromUid(Binder.getCallingUid());
4196 }
4197
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 @Override
4199 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004200 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004201 final NetworkRequest.Type type = (networkCapabilities == null)
4202 ? NetworkRequest.Type.TRACK_DEFAULT
4203 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004204 // If the requested networkCapabilities is null, take them instead from
4205 // the default network request. This allows callers to keep track of
4206 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004207 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004208 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4209 enforceAccessPermission();
4210 } else {
4211 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4212 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004213 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4214 // of the app when the request is filed, but we never change the request if the app
4215 // changes network state. http://b/29964605
4216 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004217 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004218 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004219
Etan Cohenba07c8c2017-02-05 10:42:27 -08004220 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 throw new IllegalArgumentException("Bad timeout specified");
4222 }
Etan Cohen859748f2017-04-03 17:42:34 -07004223 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004224
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004225 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004226 nextNetworkRequestId(), type);
4227 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004228 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229
4230 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004231 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004232 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004233 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004234 }
4235 return networkRequest;
4236 }
4237
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004238 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004239 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004240 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004241 } else {
4242 enforceChangePermission();
4243 }
4244 }
4245
fenglub15e72b2015-03-20 11:29:56 -07004246 @Override
fengludb571472015-04-21 17:12:05 -07004247 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004248 enforceAccessPermission();
4249 NetworkAgentInfo nai = null;
4250 if (network == null) {
4251 return false;
4252 }
4253 synchronized (mNetworkForNetId) {
4254 nai = mNetworkForNetId.get(network.netId);
4255 }
4256 if (nai != null) {
4257 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4258 return true;
4259 }
4260 return false;
4261 }
4262
Felipe Lemeee27cab2016-06-20 16:36:29 -07004263 private boolean isSystem(int uid) {
4264 return uid < Process.FIRST_APPLICATION_UID;
4265 }
fenglub15e72b2015-03-20 11:29:56 -07004266
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004267 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004268 final int uid = Binder.getCallingUid();
4269 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004270 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004271 return;
4272 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004273 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4274 // Policy already enforced.
4275 return;
4276 }
4277 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4278 // If UID is restricted, don't allow them to bring up metered APNs.
4279 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004280 }
4281 }
4282
Robert Greenwalt9258c642014-03-26 16:47:06 -07004283 @Override
4284 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4285 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004286 checkNotNull(operation, "PendingIntent cannot be null.");
4287 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4288 enforceNetworkRequestPermissions(networkCapabilities);
4289 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004290 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004291 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004292
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004293 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004294 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4295 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004296 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4298 nri));
4299 return networkRequest;
4300 }
4301
Jeremy Joslin79294842014-12-03 17:15:28 -08004302 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4303 mHandler.sendMessageDelayed(
4304 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4305 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4306 }
4307
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004308 @Override
4309 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004310 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4312 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313 }
4314
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004315 // In order to implement the compatibility measure for pre-M apps that call
4316 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4317 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4318 // This ensures it has permission to do so.
4319 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4320 if (nc == null) {
4321 return false;
4322 }
4323 int[] transportTypes = nc.getTransportTypes();
4324 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4325 return false;
4326 }
4327 try {
4328 mContext.enforceCallingOrSelfPermission(
4329 android.Manifest.permission.ACCESS_WIFI_STATE,
4330 "ConnectivityService");
4331 } catch (SecurityException e) {
4332 return false;
4333 }
4334 return true;
4335 }
4336
Robert Greenwalt9258c642014-03-26 16:47:06 -07004337 @Override
4338 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4339 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004340 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4341 enforceAccessPermission();
4342 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004343
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004344 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4345 if (!ConnectivityManager.checkChangePermission(mContext)) {
4346 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4347 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4348 // onLost and onAvailable callbacks when networks move in and out of the background.
4349 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4350 // can't request networks.
4351 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4352 }
Etan Cohen859748f2017-04-03 17:42:34 -07004353 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004354
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004355 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004356 NetworkRequest.Type.LISTEN);
4357 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004358 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004359
4360 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4361 return networkRequest;
4362 }
4363
4364 @Override
4365 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4366 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004367 checkNotNull(operation, "PendingIntent cannot be null.");
4368 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4369 enforceAccessPermission();
4370 }
Etan Cohen859748f2017-04-03 17:42:34 -07004371 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004372
Erik Kline7523eb32015-07-09 18:24:03 +09004373 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004374 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4375 NetworkRequest.Type.LISTEN);
4376 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004377 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004378
4379 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 }
4381
Erik Klineacdd6392016-07-07 16:50:58 +09004382 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004384 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004385 mHandler.sendMessage(mHandler.obtainMessage(
4386 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387 }
4388
4389 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004390 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004391 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004392 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4393 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004394 }
4395
Robert Greenwalta67be032014-05-16 15:49:14 -07004396 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004397 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004398 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4399 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4400 }
4401
4402 @Override
4403 public void unregisterNetworkFactory(Messenger messenger) {
4404 enforceConnectivityInternalPermission();
4405 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4406 }
4407
4408 private void handleUnregisterNetworkFactory(Messenger messenger) {
4409 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4410 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004411 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004412 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004413 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004414 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004415 }
4416
Robert Greenwalt7b816022014-04-18 15:25:25 -07004417 /**
4418 * NetworkAgentInfo supporting a request by requestId.
4419 * These have already been vetted (their Capabilities satisfy the request)
4420 * and the are the highest scored network available.
4421 * the are keyed off the Requests requestId.
4422 */
Hugo Benichicd952782017-09-20 11:20:14 +09004423 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4424 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4426 new SparseArray<NetworkAgentInfo>();
4427
Paul Jensen31a94f42015-02-13 14:18:39 -05004428 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4429 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004430 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4431 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004432 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4433 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4434 // there may not be a strict 1:1 correlation between the two.
4435 @GuardedBy("mNetworkForNetId")
4436 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004437
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 // NetworkAgentInfo keyed off its connecting messenger
4439 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004440 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4442 new HashMap<Messenger, NetworkAgentInfo>();
4443
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004444 @GuardedBy("mBlockedAppUids")
4445 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4446
Paul Jensen2c311d62014-11-17 12:34:51 -05004447 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 private final NetworkRequest mDefaultRequest;
4449
Erik Klineda4bfa82015-04-30 12:58:40 +09004450 // Request used to optionally keep mobile data active even when higher
4451 // priority networks like Wi-Fi are active.
4452 private final NetworkRequest mDefaultMobileDataRequest;
4453
Hugo Benichicd952782017-09-20 11:20:14 +09004454 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4455 synchronized (mNetworkForRequestId) {
4456 return mNetworkForRequestId.get(requestId);
4457 }
4458 }
4459
4460 private void clearNetworkForRequest(int requestId) {
4461 synchronized (mNetworkForRequestId) {
4462 mNetworkForRequestId.remove(requestId);
4463 }
4464 }
4465
4466 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4467 synchronized (mNetworkForRequestId) {
4468 mNetworkForRequestId.put(requestId, nai);
4469 }
4470 }
4471
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004472 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004473 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004474 }
4475
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004476 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004477 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004478 }
4479
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004480 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4481 return nri.request.requestId == mDefaultRequest.requestId;
4482 }
4483
Paul Jensen31a94f42015-02-13 14:18:39 -05004484 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004486 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004487 enforceConnectivityInternalPermission();
4488
Rubin Xu1bb5c082017-09-05 18:40:49 +01004489 LinkProperties lp = new LinkProperties(linkProperties);
4490 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004491 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4492 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004493 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004494 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4495 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004496 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004497 synchronized (this) {
4498 nai.networkMonitor.systemReady = mSystemReady;
4499 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004500 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4501 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004502 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004503 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004504 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004505 }
4506
4507 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4508 if (VDBG) log("Got NetworkAgent Messenger");
4509 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004510 synchronized (mNetworkForNetId) {
4511 mNetworkForNetId.put(na.network.netId, na);
4512 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004513 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4514 NetworkInfo networkInfo = na.networkInfo;
4515 na.networkInfo = null;
4516 updateNetworkInfo(na, networkInfo);
4517 }
4518
4519 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4520 LinkProperties newLp = networkAgent.linkProperties;
4521 int netId = networkAgent.network.netId;
4522
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004523 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4524 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004525 if (networkAgent.clatd != null) {
4526 networkAgent.clatd.fixupLinkProperties(oldLp);
4527 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004528
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004529 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 updateMtu(newLp, oldLp);
4531 // TODO - figure out what to do for clat
4532// for (LinkProperties lp : newLp.getStackedLinks()) {
4533// updateMtu(lp, null);
4534// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004535 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004536
Erik Kline94887872016-04-05 13:30:49 +09004537 updateRoutes(newLp, oldLp, netId);
4538 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004539
Hugo Benichib577d652017-06-27 15:13:20 +09004540 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004541 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004542 if (isDefaultNetwork(networkAgent)) {
4543 handleApplyDefaultProxy(newLp.getHttpProxy());
4544 } else {
4545 updateProxy(newLp, oldLp, networkAgent);
4546 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004547 // TODO - move this check to cover the whole function
4548 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004549 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004550 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4551 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004552
4553 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004554 }
4555
Joel Scherpelz668370b2017-06-08 15:35:21 +09004556 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004557 // Marks are only available on WiFi interaces. Checking for
4558 // marks on unsupported interfaces is harmless.
4559 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4560 return;
4561 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004562
Joel Scherpelz668370b2017-06-08 15:35:21 +09004563 int mark = mContext.getResources().getInteger(
4564 com.android.internal.R.integer.config_networkWakeupPacketMark);
4565 int mask = mContext.getResources().getInteger(
4566 com.android.internal.R.integer.config_networkWakeupPacketMask);
4567
4568 // Mask/mark of zero will not detect anything interesting.
4569 // Don't install rules unless both values are nonzero.
4570 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004571 return;
4572 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004573
4574 final String prefix = "iface:" + iface;
4575 try {
4576 if (add) {
4577 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4578 } else {
4579 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4580 }
4581 } catch (Exception e) {
4582 loge("Exception modifying wakeup packet monitoring: " + e);
4583 }
4584
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004585 }
4586
4587 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4588 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004589 CompareResult<String> interfaceDiff = new CompareResult<String>(
4590 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4591 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004592 for (String iface : interfaceDiff.added) {
4593 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004594 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004595 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004596 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004597 } catch (Exception e) {
4598 loge("Exception adding interface: " + e);
4599 }
4600 }
4601 for (String iface : interfaceDiff.removed) {
4602 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004603 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004604 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004605 mNetd.removeInterfaceFromNetwork(iface, netId);
4606 } catch (Exception e) {
4607 loge("Exception removing interface: " + e);
4608 }
4609 }
4610 }
4611
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004612 /**
4613 * Have netd update routes from oldLp to newLp.
4614 * @return true if routes changed between oldLp and newLp
4615 */
4616 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004617 // Compare the route diff to determine which routes should be added and removed.
4618 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4619 oldLp != null ? oldLp.getAllRoutes() : null,
4620 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004621
4622 // add routes before removing old in case it helps with continuous connectivity
4623
4624 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4625 for (RouteInfo route : routeDiff.added) {
4626 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004627 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004628 try {
4629 mNetd.addRoute(netId, route);
4630 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004631 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4632 loge("Exception in addRoute for non-gateway: " + e);
4633 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004634 }
4635 }
4636 for (RouteInfo route : routeDiff.added) {
4637 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004638 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004639 try {
4640 mNetd.addRoute(netId, route);
4641 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004642 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4643 loge("Exception in addRoute for gateway: " + e);
4644 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004645 }
4646 }
4647
4648 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004649 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004650 try {
4651 mNetd.removeRoute(netId, route);
4652 } catch (Exception e) {
4653 loge("Exception in removeRoute: " + e);
4654 }
4655 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004656 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004657 }
Erik Kline41368502015-06-17 13:19:54 +09004658
Erik Kline94887872016-04-05 13:30:49 +09004659 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4660 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4661 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 }
Erik Kline94887872016-04-05 13:30:49 +09004663
Erik Kline1742fe12017-12-13 19:40:49 +09004664 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4665 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4666
Erik Klinea24d4592018-01-11 21:07:29 +09004667 if (DBG) {
4668 final Collection<InetAddress> dnses = newLp.getDnsServers();
4669 log("Setting DNS servers for network " + netId + " to " + dnses);
4670 }
Erik Kline94887872016-04-05 13:30:49 +09004671 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004672 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004673 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004674 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004675 }
Erik Kline4edba012017-04-07 15:29:29 +09004676 }
4677
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004678 private String getNetworkPermission(NetworkCapabilities nc) {
4679 // TODO: make these permission strings AIDL constants instead.
4680 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4681 return NetworkManagementService.PERMISSION_SYSTEM;
4682 }
4683 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4684 return NetworkManagementService.PERMISSION_NETWORK;
4685 }
4686 return null;
4687 }
4688
Paul Jensen3d194ea2015-06-16 14:27:36 -04004689 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004690 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4691 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4692 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004693 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004694 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004695 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004696 if (nai.everConnected &&
4697 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4698 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004699 // does not cause any request (that is not a listen) currently matching that agent to
4700 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004701 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004702 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004703 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004704 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004705 }
4706
Paul Jensen3d194ea2015-06-16 14:27:36 -04004707 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004708 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004709 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004710 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004711 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004712 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004713 }
Paul Jensene0988542015-06-25 15:30:08 -04004714 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004715 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004716 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004717 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004718 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004719 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004720 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004721 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004722 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004723 }
4724
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004725 return newNc;
4726 }
4727
4728 /**
4729 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4730 *
4731 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4732 * capabilities we manage and store in {@code nai}, such as validated status and captive
4733 * portal status)
4734 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4735 * potentially triggers rematches.
4736 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4737 * change.)
4738 *
4739 * @param oldScore score of the network before any of the changes that prompted us
4740 * to call this function.
4741 * @param nai the network having its capabilities updated.
4742 * @param nc the new network capabilities.
4743 */
4744 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4745 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4746
4747 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004748
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004749 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004750 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004751 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004752 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004753 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004754 } catch (RemoteException e) {
4755 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004756 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004757 }
4758
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004759 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004760 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004761 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004762 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004763 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004764
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004765 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004766 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4767 // the change we're processing can't affect any requests, it can only affect the listens
4768 // on this network. We might have been called by rematchNetworkAndRequests when a
4769 // network changed foreground state.
4770 processListenRequests(nai, true);
4771 } else {
4772 // If the requestable capabilities have changed or the score changed, we can't have been
4773 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004774 rematchAllNetworksAndRequests(nai, oldScore);
4775 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004776 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004777
4778 // Report changes that are interesting for network statistics tracking.
4779 if (prevNc != null) {
4780 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004781 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004782 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004783 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004784 if (meteredChanged || roamingChanged) {
4785 notifyIfacesChangedForNetworkStats();
4786 }
4787 }
4788
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004789 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004790 // Tell VPNs about updated capabilities, since they may need to
4791 // bubble those changes through.
4792 synchronized (mVpns) {
4793 for (int i = 0; i < mVpns.size(); i++) {
4794 final Vpn vpn = mVpns.valueAt(i);
4795 vpn.updateCapabilities();
4796 }
4797 }
4798 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004799 }
4800
Hugo Benichief502882017-09-01 01:23:32 +00004801 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4802 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4803 // Ignore updates for disconnected networks
4804 return;
4805 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004806 // newLp is already a defensive copy.
4807 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004808 if (VDBG) {
4809 log("Update of LinkProperties for " + nai.name() +
4810 "; created=" + nai.created +
4811 "; everConnected=" + nai.everConnected);
4812 }
4813 LinkProperties oldLp = nai.linkProperties;
4814 synchronized (nai) {
4815 nai.linkProperties = newLp;
4816 }
4817 if (nai.everConnected) {
4818 updateLinkProperties(nai, oldLp);
4819 }
4820 }
4821
Paul Jensenc8b9a742014-09-30 15:37:41 -04004822 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004823 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4824 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004825 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004826 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004827 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4828 }
4829 }
4830
Robert Greenwalt7b816022014-04-18 15:25:25 -07004831 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4832 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004833 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004834 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4835 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004836 }
4837 }
4838
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004839 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4840 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004841 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004842 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004843 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4844 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004845 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004846 sendIntent(nri.mPendingIntent, intent);
4847 }
4848 // else not handled
4849 }
4850
4851 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4852 mPendingIntentWakeLock.acquire();
4853 try {
4854 if (DBG) log("Sending " + pendingIntent);
4855 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4856 } catch (PendingIntent.CanceledException e) {
4857 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4858 mPendingIntentWakeLock.release();
4859 releasePendingNetworkRequest(pendingIntent);
4860 }
4861 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4862 }
4863
4864 @Override
4865 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4866 String resultData, Bundle resultExtras) {
4867 if (DBG) log("Finished sending " + pendingIntent);
4868 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004869 // Release with a delay so the receiving client has an opportunity to put in its
4870 // own request.
4871 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004872 }
4873
Hugo Benichidba33db2017-03-23 22:40:44 +09004874 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004875 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004876 if (nri.messenger == null) {
4877 return; // Default request has no msgr
4878 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004879 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004880 // TODO: check if defensive copies of data is needed.
4881 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004882 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004883 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4884 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004885 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004887 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004888 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004889 break;
4890 }
4891 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004892 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004893 break;
4894 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004895 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004896 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897 break;
4898 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004900 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004901 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004902 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004903 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004904 String notification = ConnectivityManager.getCallbackName(notificationType);
4905 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004906 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004907 nri.messenger.send(msg);
4908 } catch (RemoteException e) {
4909 // may occur naturally in the race of binder death.
4910 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4911 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004912 }
4913
Hugo Benichidba33db2017-03-23 22:40:44 +09004914 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4915 bundle.putParcelable(t.getClass().getSimpleName(), t);
4916 }
4917
Paul Jensenc8b9a742014-09-30 15:37:41 -04004918 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004919 if (nai.numRequestNetworkRequests() != 0) {
4920 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4921 NetworkRequest nr = nai.requestAt(i);
4922 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004923 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004924 loge("Dead network still had at least " + nr);
4925 break;
4926 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004927 }
4928 nai.asyncChannel.disconnect();
4929 }
4930
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4932 if (oldNetwork == null) {
4933 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4934 return;
4935 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004936 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004937
4938 // If we get here it means that the last linger timeout for this network expired. So there
4939 // must be no other active linger timers, and we must stop lingering.
4940 oldNetwork.clearLingerState();
4941
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004942 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004943 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004944 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004945 } else {
4946 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004947 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4948 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004950 }
4951
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004952 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004953 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004954 setupDataActivityTracking(newNetwork);
4955 try {
4956 mNetd.setDefaultNetId(newNetwork.network.netId);
4957 } catch (Exception e) {
4958 loge("Exception setting default network :" + e);
4959 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004960 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004961 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004962 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09004963 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004964 }
4965
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004966 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004967 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4968 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4969 NetworkRequest nr = nri.request;
4970 if (!nr.isListen()) continue;
4971 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4972 nai.removeRequest(nri.request.requestId);
4973 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4974 }
4975 }
4976
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004977 if (capabilitiesChanged) {
4978 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4979 }
4980
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004981 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4982 NetworkRequest nr = nri.request;
4983 if (!nr.isListen()) continue;
4984 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4985 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004986 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004987 }
4988 }
4989 }
4990
Paul Jensen2161a8e2014-09-11 11:00:39 -04004991 // Handles a network appearing or improving its score.
4992 //
4993 // - Evaluates all current NetworkRequests that can be
4994 // satisfied by newNetwork, and reassigns to newNetwork
4995 // any such requests for which newNetwork is the best.
4996 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004997 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004998 // needed. A network is needed if it is the best network for
4999 // one or more NetworkRequests, or if it is a VPN.
5000 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005001 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005002 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005003 //
5004 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5005 // networks that have no chance (i.e. even if validated)
5006 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 //
5008 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5009 // it does not remove NetworkRequests that other Networks could better satisfy.
5010 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5011 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5012 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005013 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005014 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005015 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5016 // performed to tear down unvalidated networks that have no chance (i.e. even if
5017 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005018 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005019 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005020 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005021 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005022 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005023 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005024
5025 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5026 final int score = newNetwork.getCurrentScore();
5027
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005028 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005029
Paul Jensen2161a8e2014-09-11 11:00:39 -04005030 // Find and migrate to this Network any NetworkRequests for
5031 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005032 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005033 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005034 NetworkCapabilities nc = newNetwork.networkCapabilities;
5035 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005036 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005037 // Process requests in the first pass and listens in the second pass. This allows us to
5038 // change a network's capabilities depending on which requests it has. This is only
5039 // correct if the change in capabilities doesn't affect whether the network satisfies
5040 // requests or not, and doesn't affect the network's score.
5041 if (nri.request.isListen()) continue;
5042
Hugo Benichicd952782017-09-20 11:20:14 +09005043 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005044 final boolean satisfies = newNetwork.satisfies(nri.request);
5045 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005046 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005047 log("Network " + newNetwork.name() + " was already satisfying" +
5048 " request " + nri.request.requestId + ". No change.");
5049 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005050 keep = true;
5051 continue;
5052 }
5053
5054 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005055 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005056 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005057 // next check if it's better than any current network we're using for
5058 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 if (VDBG) {
5060 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005061 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005062 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005063 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005064 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005065 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005066 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005067 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005068 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005069 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005070 affectedNetworks.add(currentNetwork);
5071 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005072 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005073 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005074 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005075 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005076 if (!newNetwork.addRequest(nri.request)) {
5077 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5078 }
5079 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005080 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005081 // Tell NetworkFactories about the new score, so they can stop
5082 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005083 // TODO - this could get expensive if we have alot of requests for this
5084 // network. Think about if there is a way to reduce this. Push
5085 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005086 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005087 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005088 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005089 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005090 if (currentNetwork != null) {
5091 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5092 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093 }
5094 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005095 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005096 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5097 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005098 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005099 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5100 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5101 // This means this code doesn't have to handle the case where "currentNetwork" no
5102 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5103 if (DBG) {
5104 log("Network " + newNetwork.name() + " stopped satisfying" +
5105 " request " + nri.request.requestId);
5106 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005107 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005108 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005109 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005110 sendUpdatedScoreToFactories(nri.request, 0);
5111 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005112 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5113 newNetwork.name() +
5114 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005115 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005116 // TODO: Technically, sending CALLBACK_LOST here is
5117 // incorrect if there is a replacement network currently
5118 // connected that can satisfy nri, which is a request
5119 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005120 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5121 // so this code is only incorrect for a network that loses
5122 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005123 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005124 }
5125 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005126 if (isNewDefault) {
5127 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005128 makeDefault(newNetwork);
5129 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005130 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005131 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005132 // Have a new default network, release the transition wakelock in
5133 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005134 }
5135
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005136 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5137 Slog.wtf(TAG, String.format(
5138 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005139 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005140 }
5141 if (newNetwork.getCurrentScore() != score) {
5142 Slog.wtf(TAG, String.format(
5143 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005144 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005145 }
5146
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005147 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005148 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5149 // If the network went from background to foreground or vice versa, we need to update
5150 // its foreground state. It is safe to do this after rematching the requests because
5151 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5152 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005153 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005154 } else {
5155 processListenRequests(newNetwork, false);
5156 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005157
Paul Jensencf4c2c62015-07-01 14:16:32 -04005158 // do this after the default net is switched, but
5159 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005160 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005161
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005162 // Linger any networks that are no longer needed. This should be done after sending the
5163 // available callback for newNetwork.
5164 for (NetworkAgentInfo nai : affectedNetworks) {
5165 updateLingerState(nai, now);
5166 }
5167 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5168 // does not need to be done in any particular order.
5169 updateLingerState(newNetwork, now);
5170
Paul Jensencf4c2c62015-07-01 14:16:32 -04005171 if (isNewDefault) {
5172 // Maintain the illusion: since the legacy API only
5173 // understands one network at a time, we must pretend
5174 // that the current default network disconnected before
5175 // the new one connected.
5176 if (oldDefaultNetwork != null) {
5177 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5178 oldDefaultNetwork, true);
5179 }
5180 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5181 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5182 notifyLockdownVpn(newNetwork);
5183 }
5184
Robert Greenwalt7b816022014-04-18 15:25:25 -07005185 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005186 // Notify battery stats service about this network, both the normal
5187 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005188 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005189 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005190 final IBatteryStats bs = BatteryStatsService.getService();
5191 final int type = newNetwork.networkInfo.getType();
5192
5193 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5194 bs.noteNetworkInterfaceType(baseIface, type);
5195 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5196 final String stackedIface = stacked.getInterfaceName();
5197 bs.noteNetworkInterfaceType(stackedIface, type);
5198 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5199 }
5200 } catch (RemoteException ignored) {
5201 }
5202
Robert Greenwalt152ed372014-12-17 17:19:53 -08005203 // This has to happen after the notifyNetworkCallbacks as that tickles each
5204 // ConnectivityManager instance so that legacy requests correctly bind dns
5205 // requests to this network. The legacy users are listening for this bcast
5206 // and will generally do a dns request so they can ensureRouteToHost and if
5207 // they do that before the callbacks happen they'll use the default network.
5208 //
5209 // TODO: Is there still a race here? We send the broadcast
5210 // after sending the callback, but if the app can receive the
5211 // broadcast before the callback, it might still break.
5212 //
5213 // This *does* introduce a race where if the user uses the new api
5214 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5215 // they may get old info. Reverse this after the old startUsing api is removed.
5216 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005217 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5218 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005219 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005220 // legacy type tracker filters out repeat adds
5221 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5222 }
5223 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005224
5225 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5226 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5227 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5228 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5229 if (newNetwork.isVPN()) {
5230 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5231 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005233 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5234 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005235 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005236 if (nai.getLingerExpiry() > 0) {
5237 // This network has active linger timers and no requests, but is not
5238 // lingering. Linger it.
5239 //
5240 // One way (the only way?) this can happen if this network is unvalidated
5241 // and became unneeded due to another network improving its score to the
5242 // point where this network will no longer be able to satisfy any requests
5243 // even if it validates.
5244 updateLingerState(nai, now);
5245 } else {
5246 if (DBG) log("Reaping " + nai.name());
5247 teardownUnneededNetwork(nai);
5248 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005249 }
5250 }
5251 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005252 }
5253
Paul Jensen1c7ba022015-06-16 14:27:36 -04005254 /**
5255 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5256 * being disconnected.
5257 * @param changed If only one Network's score or capabilities have been modified since the last
5258 * time this function was called, pass this Network in this argument, otherwise pass
5259 * null.
5260 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5261 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5262 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5263 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5264 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005265 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005266 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005267 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5268 // to avoid the slowness. It is not simply enough to process just "changed", for
5269 // example in the case where "changed"'s score decreases and another network should begin
5270 // satifying a NetworkRequest that "changed" currently satisfies.
5271
5272 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5273 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5274 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005275 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005276 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005277 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005278 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005279 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5280 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5281 // Rematch higher scoring networks first to prevent requests first matching a lower
5282 // scoring network and then a higher scoring network, which could produce multiple
5283 // callbacks and inadvertently unlinger networks.
5284 Arrays.sort(nais);
5285 for (NetworkAgentInfo nai : nais) {
5286 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005287 // Only reap the last time through the loop. Reaping before all rematching
5288 // is complete could incorrectly teardown a network that hasn't yet been
5289 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005290 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005291 : ReapUnvalidatedNetworks.REAP,
5292 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005293 }
5294 }
5295 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005296
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005297 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005298 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005299 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005300 // For now only update icons for default connection.
5301 // TODO: Update WiFi and cellular icons separately. b/17237507
5302 if (!isDefaultNetwork(nai)) return;
5303
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005304 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005305 // Don't repeat publish.
5306 if (newInetCondition == mDefaultInetConditionPublished) return;
5307
5308 mDefaultInetConditionPublished = newInetCondition;
5309 sendInetConditionBroadcast(nai.networkInfo);
5310 }
5311
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005312 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005313 synchronized (mVpns) {
5314 if (mLockdownTracker != null) {
5315 if (nai != null && nai.isVPN()) {
5316 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5317 } else {
5318 mLockdownTracker.onNetworkInfoChanged();
5319 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005320 }
5321 }
5322 }
5323
Robert Greenwalt7b816022014-04-18 15:25:25 -07005324 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005325 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005326 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005327 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005328 synchronized (networkAgent) {
5329 oldInfo = networkAgent.networkInfo;
5330 networkAgent.networkInfo = newInfo;
5331 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005332 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005333
Robert Greenwalt7b816022014-04-18 15:25:25 -07005334 if (DBG) {
5335 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5336 (oldInfo == null ? "null" : oldInfo.getState()) +
5337 " to " + state);
5338 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005339
Robin Lee585e2482016-05-01 23:00:00 +01005340 if (!networkAgent.created
5341 && (state == NetworkInfo.State.CONNECTED
5342 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005343
5344 // A network that has just connected has zero requests and is thus a foreground network.
5345 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5346
Robert Greenwalt7b816022014-04-18 15:25:25 -07005347 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005348 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005349 if (networkAgent.isVPN()) {
5350 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005351 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5352 (networkAgent.networkMisc == null ||
5353 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005354 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005355 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005356 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005357 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005358 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005359 loge("Error creating network " + networkAgent.network.netId + ": "
5360 + e.getMessage());
5361 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005362 }
Paul Jenseneec75412014-08-04 12:21:19 -04005363 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005364 }
5365
5366 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5367 networkAgent.everConnected = true;
5368
Robert Greenwalt7b816022014-04-18 15:25:25 -07005369 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005370 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005371
Paul Jensenca8f16a2014-05-09 12:47:55 -04005372 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005373 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005374
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005375 if (networkAgent.isVPN()) {
5376 // Temporarily disable the default proxy (not global).
5377 synchronized (mProxyLock) {
5378 if (!mDefaultProxyDisabled) {
5379 mDefaultProxyDisabled = true;
5380 if (mGlobalProxy == null && mDefaultProxy != null) {
5381 sendProxyBroadcast(null);
5382 }
5383 }
5384 }
5385 // TODO: support proxy per network.
5386 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005387
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005388 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5389 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5390 // capabilities, so it only needs to be done once on initial connect, not every time the
5391 // network's capabilities change. Note that we do this before rematching the network,
5392 // so we could decide to tear it down immediately afterwards. That's fine though - on
5393 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5394 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005395 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005396
Paul Jensen2161a8e2014-09-11 11:00:39 -04005397 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005398 final long now = SystemClock.elapsedRealtime();
5399 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005400
5401 // This has to happen after matching the requests, because callbacks are just requests.
5402 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005403 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005404 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005405 if (networkAgent.isVPN()) {
5406 synchronized (mProxyLock) {
5407 if (mDefaultProxyDisabled) {
5408 mDefaultProxyDisabled = false;
5409 if (mGlobalProxy == null && mDefaultProxy != null) {
5410 sendProxyBroadcast(mDefaultProxy);
5411 }
5412 }
5413 }
5414 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005415 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5416 state == NetworkInfo.State.SUSPENDED) {
5417 // going into or coming out of SUSPEND: rescore and notify
5418 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005419 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005420 }
5421 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5422 ConnectivityManager.CALLBACK_SUSPENDED :
5423 ConnectivityManager.CALLBACK_RESUMED));
5424 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005425 }
5426 }
5427
Robert Greenwaltac96c522014-06-03 16:43:57 -07005428 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005429 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005430 if (score < 0) {
5431 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5432 "). Bumping score to min of 0");
5433 score = 0;
5434 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005435
Paul Jensen2161a8e2014-09-11 11:00:39 -04005436 final int oldScore = nai.getCurrentScore();
5437 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005438
Paul Jensen85cf78e2015-06-25 13:25:07 -04005439 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005440
Paul Jensenc8b9a742014-09-30 15:37:41 -04005441 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005442 }
5443
Erik Klinec75d4fa2017-02-15 19:59:17 +09005444 // Notify only this one new request of the current state. Transfer all the
5445 // current state by calling NetworkCapabilities and LinkProperties callbacks
5446 // so that callers can be guaranteed to have as close to atomicity in state
5447 // transfer as can be supported by this current API.
5448 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005449 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005450 if (nri.mPendingIntent != null) {
5451 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5452 // Attempt no subsequent state pushes where intents are involved.
5453 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005454 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005455
5456 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5457 // Whether a network is currently suspended is also an important
5458 // element of state to be transferred (it would not otherwise be
5459 // delivered by any currently available mechanism).
5460 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5461 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5462 }
5463 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5464 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005465 }
5466
Robert Greenwalt8d482522015-06-24 13:23:42 -07005467 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005468 // The NetworkInfo we actually send out has no bearing on the real
5469 // state of affairs. For example, if the default connection is mobile,
5470 // and a request for HIPRI has just gone away, we need to pretend that
5471 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5472 // the state to DISCONNECTED, even though the network is of type MOBILE
5473 // and is still connected.
5474 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5475 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005476 if (state != DetailedState.DISCONNECTED) {
5477 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005478 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005479 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005480 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005481 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5482 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5483 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5484 if (info.isFailover()) {
5485 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5486 nai.networkInfo.setFailover(false);
5487 }
5488 if (info.getReason() != null) {
5489 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5490 }
5491 if (info.getExtraInfo() != null) {
5492 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5493 }
5494 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005495 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005496 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005497 if (newDefaultAgent != null) {
5498 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5499 newDefaultAgent.networkInfo);
5500 } else {
5501 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5502 }
5503 }
5504 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5505 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005506 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005507 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005508 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005509 }
5510 }
5511 }
5512
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005513 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005514 if (VDBG) {
5515 String notification = ConnectivityManager.getCallbackName(notifyType);
5516 log("notifyType " + notification + " for " + networkAgent.name());
5517 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005518 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5519 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005520 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5521 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005522 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5523 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005524 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005525 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005526 } else {
5527 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5528 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005529 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005530 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005531
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005532 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5533 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5534 }
5535
Jeff Sharkey69736342014-12-08 14:50:12 -08005536 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005537 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5538 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005539 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005540 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005541 try {
5542 mStatsService.forceUpdateIfaces();
5543 } catch (Exception ignored) {
5544 }
5545 }
5546
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005547 @Override
5548 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005549 int user = UserHandle.getUserId(Binder.getCallingUid());
5550 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005551 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005552 return mVpns.get(user).addAddress(address, prefixLength);
5553 }
5554 }
5555
5556 @Override
5557 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005558 int user = UserHandle.getUserId(Binder.getCallingUid());
5559 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005560 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005561 return mVpns.get(user).removeAddress(address, prefixLength);
5562 }
5563 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005564
5565 @Override
5566 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005567 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005568 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005569 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005570 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005571 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005572 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005573 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005574 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005575 }
5576 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005577 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005578
5579 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005580 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005581 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005582 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005583 }
5584
5585 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005586 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5587 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5588 enforceKeepalivePermission();
5589 mKeepaliveTracker.startNattKeepalive(
5590 getNetworkAgentInfoForNetwork(network),
5591 intervalSeconds, messenger, binder,
5592 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5593 }
5594
5595 @Override
5596 public void stopKeepalive(Network network, int slot) {
5597 mHandler.sendMessage(mHandler.obtainMessage(
5598 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5599 }
5600
5601 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005602 public void factoryReset() {
5603 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005604
5605 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5606 return;
5607 }
5608
Robin Lee3b3dd942015-05-12 18:14:58 +01005609 final int userId = UserHandle.getCallingUserId();
5610
Stuart Scottf1fb3972015-04-02 18:00:02 -07005611 // Turn airplane mode off
5612 setAirplaneMode(false);
5613
Stuart Scotte3e314d2015-04-20 14:07:45 -07005614 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5615 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005616 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005617 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005618 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005619 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005620 }
5621
Stuart Scotte3e314d2015-04-20 14:07:45 -07005622 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005623 // Remove always-on package
5624 synchronized (mVpns) {
5625 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5626 if (alwaysOnPackage != null) {
5627 setAlwaysOnVpnPackage(userId, null, false);
5628 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5629 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005630
Hugo Benichi69744342017-11-27 10:57:16 +09005631 // Turn Always-on VPN off
5632 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5633 final long ident = Binder.clearCallingIdentity();
5634 try {
5635 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5636 mLockdownEnabled = false;
5637 setLockdownTracker(null);
5638 } finally {
5639 Binder.restoreCallingIdentity(ident);
5640 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005641 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005642
Hugo Benichi69744342017-11-27 10:57:16 +09005643 // Turn VPN off
5644 VpnConfig vpnConfig = getVpnConfig(userId);
5645 if (vpnConfig != null) {
5646 if (vpnConfig.legacy) {
5647 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5648 } else {
5649 // Prevent this app (packagename = vpnConfig.user) from initiating
5650 // VPN connections in the future without user intervention.
5651 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005652
Hugo Benichi69744342017-11-27 10:57:16 +09005653 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5654 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005655 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005656 }
5657 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005658
5659 Settings.Global.putString(mContext.getContentResolver(),
5660 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005661 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005662
5663 @VisibleForTesting
5664 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5665 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5666 return new NetworkMonitor(context, handler, nai, defaultRequest);
5667 }
Erik Kline48f12f22016-04-14 17:30:59 +09005668
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005669 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005670 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5671 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005672 }
5673
5674 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005675 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5676 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5677 }
5678
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005679 @VisibleForTesting
5680 public boolean hasService(String name) {
5681 return ServiceManager.checkService(name) != null;
5682 }
5683
Hugo Benichi64901e52017-10-19 14:42:40 +09005684 @VisibleForTesting
5685 protected IpConnectivityMetrics.Logger metricsLogger() {
5686 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5687 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005688 }
5689
5690 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005691 int[] transports = nai.networkCapabilities.getTransportTypes();
5692 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005693 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005694
5695 private static boolean toBool(int encodedBoolean) {
5696 return encodedBoolean != 0; // Only 0 means false.
5697 }
5698
5699 private static int encodeBool(boolean b) {
5700 return b ? 1 : 0;
5701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702}