blob: bccae062811c14cba49eee587d0fbf01f762355c [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;
Charles He36738632017-05-15 17:07:18 +010058import 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 Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070067import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070068import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070069import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070071import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040072import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070073import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040074import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040075import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060076import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090077import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090078import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090079import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080081import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070082import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040083import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070085import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070087import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Looper;
89import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070090import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070091import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090092import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080096import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090097import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090098import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090099import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700111import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500112import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Wink Savilleab9321d2013-06-29 21:10:57 -0700116import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700120import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700122import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800123import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700124import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700125import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600126import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900129import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400132import com.android.server.connectivity.DataConnectionStats;
Hugo Benichi64901e52017-10-19 14:42:40 +0900133import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900134import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100135import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700136import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700137import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600138import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400139import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900140import com.android.server.connectivity.NetworkNotificationManager;
141import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400142import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700143import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800144import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700145import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100146import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700147import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700148import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900149import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700150import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600151
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700152import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700153
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import org.xmlpull.v1.XmlPullParser;
155import org.xmlpull.v1.XmlPullParserException;
156
157import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700159import java.io.FileNotFoundException;
160import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700161import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700163import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.net.InetAddress;
165import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700166import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700168import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700169import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700170import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700171import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700172import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700173import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700174import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600175import java.util.SortedSet;
176import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178/**
179 * @hide
180 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800181public class ConnectivityService extends IConnectivityManager.Stub
182 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900183 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Erik Kline7747fd42017-05-12 16:52:48 +0900185 public static final String DIAG_ARG = "--diag";
186 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900187 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900188
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900189 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700190 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Jake Hamby786e71a2014-02-06 14:43:50 -0800192 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900193 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700194
Jeff Sharkey899223b2012-08-04 15:24:58 -0700195 // TODO: create better separation between radio types and network types
196
Robert Greenwalt42acef32009-08-12 16:08:25 -0700197 // how long to wait before switching back to a radio's default network
198 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
199 // system property that can override the above value
200 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
201 "android.telephony.apn-restore";
202
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900203 // How long to wait before putting up a "This network doesn't have an Internet connection,
204 // connect anyway?" dialog after the user selects a network that doesn't validate.
205 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
206
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900207 // Default to 30s linger time-out. Modifiable only for testing.
208 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
209 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
210 @VisibleForTesting
211 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
212
Jeremy Joslin79294842014-12-03 17:15:28 -0800213 // How long to delay to removal of a pending intent based request.
214 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
215 private final int mReleasePendingIntentDelayMs;
216
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900217 private MockableSystemProperties mSystemProperties;
218
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800219 private Tethering mTethering;
220
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700221 private final PermissionMonitor mPermissionMonitor;
222
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700223 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700224
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700225 @GuardedBy("mVpns")
226 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700227
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700228 private boolean mLockdownEnabled;
229 private LockdownVpnTracker mLockdownTracker;
230
Erik Klineda4bfa82015-04-30 12:58:40 +0900231 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700233 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700234 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800236 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700239 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700241 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800242 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700243 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900244 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700246 private String mCurrentTcpBufferSizes;
247
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700248 private static final int ENABLED = 1;
249 private static final int DISABLED = 0;
250
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900251 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900252 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
253 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254
Paul Jensenb10e37f2014-11-25 12:33:08 -0500255 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Tear down networks that have no chance (e.g. even if validated) of becoming
257 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 // all networks have been rematched against all NetworkRequests.
259 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Don't reap networks. This should be passed when some networks have not yet been
261 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 DONT_REAP
263 };
264
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900265 private enum UnneededFor {
266 LINGER, // Determine whether this network is unneeded and should be lingered.
267 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
268 }
269
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700271 * used internally to change our mobile data enabled flag
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274
275 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700276 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700277 * from one net to another. Clear happens when we get a new
278 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
279 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700282
Robert Greenwalt434203a2010-10-11 16:00:27 -0700283 /**
284 * used internally to reload global proxy settings
285 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700286 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700287
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700288 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400289 * PAC manager has received new port.
290 */
291 private static final int EVENT_PROXY_HAS_CHANGED = 16;
292
Robert Greenwalte049c232014-04-11 15:53:27 -0700293 /**
294 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700295 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 */
297 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
298
Robert Greenwalt7b816022014-04-18 15:25:25 -0700299 /**
300 * used internally when registering NetworkAgents
301 * obj = Messenger
302 */
303 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
304
Robert Greenwalt9258c642014-03-26 16:47:06 -0700305 /**
306 * used to add a network request
307 * includes a NetworkRequestInfo
308 */
309 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
310
311 /**
312 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900313 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700314 * cancel it.
315 * includes a NetworkRequestInfo
316 */
317 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
318
319 /**
320 * used to add a network listener - no request
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
324
325 /**
326 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400327 * arg1 = UID of caller
328 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700329 */
330 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
331
Robert Greenwalta67be032014-05-16 15:49:14 -0700332 /**
333 * used internally when registering NetworkFactories
334 * obj = Messenger
335 */
336 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
337
Robert Greenwalt27711812014-06-25 16:45:57 -0700338 /**
339 * used internally to expire a wakelock when transitioning
340 * from one net to another. Expire happens when we fail to find
341 * a new network (typically after 1 minute) -
342 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
343 * a replacement network.
344 */
345 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
346
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700347 /**
348 * Used internally to indicate the system is ready.
349 */
350 private static final int EVENT_SYSTEM_READY = 25;
351
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800352 /**
353 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400354 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 */
356 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
357
358 /**
359 * used to remove a pending intent and its associated network request.
360 * arg1 = UID of caller
361 * obj = PendingIntent
362 */
363 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
364
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900365 /**
366 * used to specify whether a network should be used even if unvalidated.
367 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
368 * arg2 = whether to remember this choice in the future (1 or 0)
369 * obj = network
370 */
371 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
372
373 /**
374 * used to ask the user to confirm a connection to an unvalidated network.
375 * obj = network
376 */
377 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700378
Erik Klineda4bfa82015-04-30 12:58:40 +0900379 /**
380 * used internally to (re)configure mobile data always-on settings.
381 */
382 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
383
Paul Jensen694f2b82015-06-17 14:15:39 -0400384 /**
385 * used to add a network listener with a pending intent
386 * obj = NetworkRequestInfo
387 */
388 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
389
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900390 /**
391 * used to specify whether a network should not be penalized when it becomes unvalidated.
392 */
393 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
394
395 /**
396 * used to trigger revalidation of a network.
397 */
398 private static final int EVENT_REVALIDATE_NETWORK = 36;
399
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900400 private static String eventName(int what) {
401 return sMagicDecoderRing.get(what, Integer.toString(what));
402 }
403
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900404 /** Handler thread used for both of the handlers below. */
405 @VisibleForTesting
406 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700407 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700408 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700409 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700410 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411
Mike Lockwood0f79b542009-08-14 14:18:49 -0400412 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800413 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400414
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800417 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700418
Robert Greenwalt434203a2010-10-11 16:00:27 -0700419 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400420 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700421 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700422 private boolean mDefaultProxyDisabled = false;
423
Robert Greenwalt434203a2010-10-11 16:00:27 -0700424 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400425 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426
Jason Monk602b2322013-07-03 17:04:33 -0400427 private PacManager mPacManager = null;
428
Erik Klineda4bfa82015-04-30 12:58:40 +0900429 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700430
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400431 private UserManager mUserManager;
432
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700433 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700435
Robert Greenwalt50393202011-06-21 17:26:14 -0700436 // the set of network types that can only be enabled by system/sig apps
437 List mProtectedNetworks;
438
John Spurlockbf991a82013-06-24 14:20:23 -0400439 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700440
Wink Savilleab9321d2013-06-29 21:10:57 -0700441 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400442
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900443 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900444 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900445 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900446
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700447 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
448 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700449 private final static int MAX_NET_ID = 65535;
450 private int mNextNetId = MIN_NET_ID;
451
Robert Greenwalt34524f02014-05-18 16:22:10 -0700452 // sequence number of NetworkRequests
453 private int mNextNetworkRequestId = 1;
454
Erik Kline7523eb32015-07-09 18:24:03 +0900455 // NetworkRequest activity String log entries.
456 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
457 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
458
Hugo Benichic2ae2872016-07-11 11:05:12 +0900459 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900460 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900461 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
462
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900463 private static final int MAX_WAKELOCK_LOGS = 20;
464 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900465 private int mTotalWakelockAcquisitions = 0;
466 private int mTotalWakelockReleases = 0;
467 private long mTotalWakelockDurationMs = 0;
468 private long mMaxWakelockDurationMs = 0;
469 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900470
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
472 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 private static class ValidationLog {
474 final Network mNetwork;
475 final String mNetworkExtraInfo;
476 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700477
Paul Jensen0808eb82016-06-03 13:51:21 -0400478 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
479 mNetwork = network;
480 mNetworkExtraInfo = networkExtraInfo;
481 mLog = log;
482 }
483 }
484 private final ArrayDeque<ValidationLog> mValidationLogs =
485 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
486
487 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900488 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
490 mValidationLogs.removeLast();
491 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400492 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700493 }
494 }
495
Hugo Benichif9fdf872016-07-28 17:53:06 +0900496 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900497
Erik Kline065ab6e2016-10-02 18:02:14 +0900498 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900499 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900500
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700501 /**
502 * Implements support for the legacy "one network per network type" model.
503 *
504 * We used to have a static array of NetworkStateTrackers, one for each
505 * network type, but that doesn't work any more now that we can have,
506 * for example, more that one wifi network. This class stores all the
507 * NetworkAgentInfo objects that support a given type, but the legacy
508 * API will only see the first one.
509 *
510 * It serves two main purposes:
511 *
512 * 1. Provide information about "the network for a given type" (since this
513 * API only supports one).
514 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
515 * the first network for a given type changes, or if the default network
516 * changes.
517 */
518 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900519
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900520 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523 /**
524 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
525 * Each list holds references to all NetworkAgentInfos that are used to
526 * satisfy requests for that network type.
527 *
528 * This array is built out at startup such that an unsupported network
529 * doesn't get an ArrayList instance, making this a tristate:
530 * unsupported, supported but not active and active.
531 *
532 * The actual lists are populated when we scan the network types that
533 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900534 *
535 * Threading model:
536 * - addSupportedType() is only called in the constructor
537 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
538 * They are therefore not thread-safe with respect to each other.
539 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
540 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
541 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700542 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900543 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544
545 public LegacyTypeTracker() {
546 mTypeLists = (ArrayList<NetworkAgentInfo>[])
547 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
548 }
549
550 public void addSupportedType(int type) {
551 if (mTypeLists[type] != null) {
552 throw new IllegalStateException(
553 "legacy list for type " + type + "already initialized");
554 }
555 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
556 }
557
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 public boolean isTypeSupported(int type) {
559 return isNetworkTypeValid(type) && mTypeLists[type] != null;
560 }
561
562 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 synchronized (mTypeLists) {
564 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
565 return mTypeLists[type].get(0);
566 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700567 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900568 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700569 }
570
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900572 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900573 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900576 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900577 }
578 }
579
580 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700581 public void add(int type, NetworkAgentInfo nai) {
582 if (!isTypeSupported(type)) {
583 return; // Invalid network type.
584 }
585 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
586
587 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
588 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700589 return;
590 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900591 synchronized (mTypeLists) {
592 list.add(nai);
593 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900594
595 // 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 +0900596 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900597 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700598 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
599 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700601 }
602
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900604 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
606 if (list == null || list.isEmpty()) {
607 return;
608 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900609 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610
Hugo Benichi78caa2582016-06-21 09:48:07 +0900611 synchronized (mTypeLists) {
612 if (!list.remove(nai)) {
613 return;
614 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900615 }
616
Robert Greenwalt8d482522015-06-24 13:23:42 -0700617 final DetailedState state = DetailedState.DISCONNECTED;
618
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900619 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 maybeLogBroadcast(nai, state, type, wasDefault);
621 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 }
623
624 if (!list.isEmpty() && wasFirstNetwork) {
625 if (DBG) log("Other network available for type " + type +
626 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900627 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
629 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900630 }
631 }
632
633 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
635 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700636 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700638 }
639 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700640
Robert Greenwalt8d482522015-06-24 13:23:42 -0700641 // send out another legacy broadcast - currently only used for suspend/unsuspend
642 // toggle
643 public void update(NetworkAgentInfo nai) {
644 final boolean isDefault = isDefaultNetwork(nai);
645 final DetailedState state = nai.networkInfo.getDetailedState();
646 for (int type = 0; type < mTypeLists.length; type++) {
647 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700648 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900649 final boolean isFirst = contains && (nai == list.get(0));
650 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700651 maybeLogBroadcast(nai, state, type, isDefault);
652 sendLegacyNetworkBroadcast(nai, state, type);
653 }
654 }
655 }
656
Lorenzo Colittia793a672014-07-31 23:20:17 +0900657 private String naiToString(NetworkAgentInfo nai) {
658 String name = (nai != null) ? nai.name() : "null";
659 String state = (nai.networkInfo != null) ?
660 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
661 "???/???";
662 return name + " " + state;
663 }
664
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 pw.println("mLegacyTypeTracker:");
667 pw.increaseIndent();
668 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700669 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900670 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700671 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900672 pw.println();
673 pw.println("Current state:");
674 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900675 synchronized (mTypeLists) {
676 for (int type = 0; type < mTypeLists.length; type++) {
677 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
678 for (NetworkAgentInfo nai : mTypeLists[type]) {
679 pw.println(type + " " + naiToString(nai));
680 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900681 }
682 }
683 pw.decreaseIndent();
684 pw.decreaseIndent();
685 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700687 }
688 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
689
Vishnu Nair5c010902017-10-26 10:08:50 -0700690 /**
691 * Helper class which parses out priority arguments and dumps sections according to their
692 * priority. If priority arguments are omitted, function calls the legacy dump command.
693 */
694 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
695 @Override
696 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
697 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
698 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
699 }
700
701 @Override
702 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
703 doDump(fd, pw, args, asProto);
704 }
705
706 @Override
707 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
708 doDump(fd, pw, args, asProto);
709 }
710 };
711
Jeff Sharkey899223b2012-08-04 15:24:58 -0700712 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700713 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900714 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
715 }
716
717 @VisibleForTesting
718 protected ConnectivityService(Context context, INetworkManagementService netManager,
719 INetworkStatsService statsService, INetworkPolicyManager policyManager,
720 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800721 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800722
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900723 mSystemProperties = getSystemProperties();
724
Hugo Benichif9fdf872016-07-28 17:53:06 +0900725 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900726 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900727 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900728 mNetworkRequests.put(mDefaultRequest, defaultNRI);
729 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900730
731 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900732 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700733
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900734 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900735 mHandlerThread.start();
736 mHandler = new InternalHandler(mHandlerThread.getLooper());
737 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700738
Jeremy Joslin79294842014-12-03 17:15:28 -0800739 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
740 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
741
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900742 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900743
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700744 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700745 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800746 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700747 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900748 mPolicyManagerInternal = checkNotNull(
749 LocalServices.getService(NetworkPolicyManagerInternal.class),
750 "missing NetworkPolicyManagerInternal");
751
Jeff Sharkey82f85212012-08-24 11:17:25 -0700752 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700753 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700754
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700755 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900756 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700757 } catch (RemoteException e) {
758 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700759 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700760 }
761
762 final PowerManager powerManager = (PowerManager) context.getSystemService(
763 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700764 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
765 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
766 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800767 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700768
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700769 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700770
Wink Saville51f456f2013-04-23 14:26:51 -0700771 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900772 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700773 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 String[] naStrings = context.getResources().getStringArray(
775 com.android.internal.R.array.networkAttributes);
776 for (String naString : naStrings) {
777 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700778 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700779 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700780 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800781 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700782 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700784 }
Wink Saville51f456f2013-04-23 14:26:51 -0700785 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
786 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
787 n.type);
788 continue;
789 }
Wink Saville975c8482011-04-07 14:23:45 -0700790 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800791 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700792 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700793 continue;
794 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700795 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700796
Wink Saville975c8482011-04-07 14:23:45 -0700797 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700798 mNetworksDefined++;
799 } catch(Exception e) {
800 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700801 }
802 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700803
804 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
805 if (mNetConfigs[TYPE_VPN] == null) {
806 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
807 // don't need to add TYPE_VPN to mNetConfigs.
808 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
809 mNetworksDefined++; // used only in the log() statement below.
810 }
811
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900812 // Do the same for Ethernet, since it's often not specified in the configs, although many
813 // devices can use it via USB host adapters.
814 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
815 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
816 mNetworksDefined++;
817 }
818
Wink Saville5e56bc52013-07-29 15:00:57 -0700819 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700820
Robert Greenwalt50393202011-06-21 17:26:14 -0700821 mProtectedNetworks = new ArrayList<Integer>();
822 int[] protectedNetworks = context.getResources().getIntArray(
823 com.android.internal.R.array.config_protectedNetworks);
824 for (int p : protectedNetworks) {
825 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
826 mProtectedNetworks.add(p);
827 } else {
828 if (DBG) loge("Ignoring protectedNetwork " + p);
829 }
830 }
831
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900832 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
833 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700834
Erik Kline47222fc2017-04-30 19:36:15 +0900835 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800836
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700837 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
838
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700839 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700840 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100841 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700842 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700843 intentFilter.addAction(Intent.ACTION_USER_ADDED);
844 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000845 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700846 mContext.registerReceiverAsUser(
847 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000848 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
849 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900850
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700851 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700852 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700853 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700854 } catch (RemoteException e) {
855 loge("Error registering observer :" + e);
856 }
857
Erik Klineda4bfa82015-04-30 12:58:40 +0900858 mSettingsObserver = new SettingsObserver(mContext, mHandler);
859 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800860
John Spurlockbf991a82013-06-24 14:20:23 -0400861 mDataConnectionStats = new DataConnectionStats(mContext);
862 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400863
Jason Monkdecd2952013-10-10 14:02:51 -0400864 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700865
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400866 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900867
868 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900869 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
870 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900871
872 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
873 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
874 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
875 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
876 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
877 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
878 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900879
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900880 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900881 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900882 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700884
Erik Kline47222fc2017-04-30 19:36:15 +0900885 private Tethering makeTethering() {
886 // TODO: Move other elements into @Overridden getters.
887 final TetheringDependencies deps = new TetheringDependencies();
888 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
889 IoThread.get().getLooper(), new MockableSystemProperties(),
890 deps);
891 }
892
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900893 private NetworkRequest createInternetRequestForTransport(
894 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900895 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900896 netCap.addCapability(NET_CAPABILITY_INTERNET);
897 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900898 if (transportType > -1) {
899 netCap.addTransportType(transportType);
900 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900901 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900902 }
903
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900904 // Used only for testing.
905 // TODO: Delete this and either:
906 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
907 // changing ContentResolver to make registerContentObserver non-final).
908 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
909 // by subclassing SettingsObserver.
910 @VisibleForTesting
911 void updateMobileDataAlwaysOn() {
912 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
913 }
914
Erik Klineda4bfa82015-04-30 12:58:40 +0900915 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900916 final boolean enable = toBool(Settings.Global.getInt(
917 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900918 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
919 if (enable == isEnabled) {
920 return; // Nothing to do.
921 }
922
923 if (enable) {
924 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900925 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900926 } else {
927 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
928 }
929 }
930
931 private void registerSettingsCallbacks() {
932 // Watch for global HTTP proxy changes.
933 mSettingsObserver.observe(
934 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
935 EVENT_APPLY_GLOBAL_HTTP_PROXY);
936
937 // Watch for whether or not to keep mobile data always on.
938 mSettingsObserver.observe(
939 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
940 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
941 }
942
Robert Greenwalt34524f02014-05-18 16:22:10 -0700943 private synchronized int nextNetworkRequestId() {
944 return mNextNetworkRequestId++;
945 }
946
Paul Jensen67b0b072015-06-10 11:22:17 -0400947 @VisibleForTesting
948 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400949 synchronized (mNetworkForNetId) {
950 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
951 int netId = mNextNetId;
952 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
953 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500954 if (!mNetIdInUse.get(netId)) {
955 mNetIdInUse.put(netId, true);
956 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400957 }
958 }
959 }
960 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700961 }
962
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600963 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600965 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
966 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 state = nai.getNetworkState();
969 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800970 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600971 final NetworkInfo info = new NetworkInfo(networkType, 0,
972 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
974 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600975 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
976 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600978 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600979 return state;
980 } else {
981 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400983 }
984
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
986 if (network == null) {
987 return null;
988 }
989 synchronized (mNetworkForNetId) {
990 return mNetworkForNetId.get(network.netId);
991 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600992 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900994 private Network[] getVpnUnderlyingNetworks(int uid) {
995 if (!mLockdownEnabled) {
996 int user = UserHandle.getUserId(uid);
997 synchronized (mVpns) {
998 Vpn vpn = mVpns.get(user);
999 if (vpn != null && vpn.appliesToUid(uid)) {
1000 return vpn.getUnderlyingNetworks();
1001 }
1002 }
1003 }
1004 return null;
1005 }
1006
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001008 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001009
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001010 final Network[] networks = getVpnUnderlyingNetworks(uid);
1011 if (networks != null) {
1012 // getUnderlyingNetworks() returns:
1013 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1014 // empty array => the VPN explicitly said "no default network".
1015 // non-empty array => the VPN specified one or more default networks; we use the
1016 // first one.
1017 if (networks.length > 0) {
1018 nai = getNetworkAgentInfoForNetwork(networks[0]);
1019 } else {
1020 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001021 }
1022 }
1023
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001025 return nai.getNetworkState();
1026 } else {
1027 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001029 }
1030
1031 /**
1032 * Check if UID should be blocked from using the network with the given LinkProperties.
1033 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001034 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1035 boolean ignoreBlocked) {
1036 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001037 if (ignoreBlocked) {
1038 return false;
1039 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001040 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001041 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1042 if (isSystem(uid)) {
1043 return false;
1044 }
Robin Lee17e61832016-05-09 13:46:28 +01001045 synchronized (mVpns) {
1046 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1047 if (vpn != null && vpn.isBlockingUid(uid)) {
1048 return true;
1049 }
1050 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001051 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001052 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 }
1054
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001055 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001056 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1057 return;
1058 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001059 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001060 synchronized (mBlockedAppUids) {
1061 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001062 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001063 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001064 blocked = false;
1065 } else {
1066 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001067 }
1068 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001069 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1070 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1071 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001072 }
1073
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001075 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1076 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001077 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001078 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001080 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1081
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 if (mLockdownTracker != null) {
1086 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
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
1251 if (!mLockdownEnabled) {
1252 synchronized (mVpns) {
1253 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
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001482 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
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
1488 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001489 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001490 @Override
1491 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001492 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001493 if (restrictBackground) {
1494 log("onRestrictBackgroundChanged(true): disabling tethering");
1495 mTethering.untetherAll();
1496 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001497 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001498 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001499 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001500 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001501 };
1502
Robin Lee3b3dd942015-05-12 18:14:58 +01001503 /**
1504 * Require that the caller is either in the same user or has appropriate permission to interact
1505 * across users.
1506 *
1507 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1508 */
1509 private void enforceCrossUserPermission(int userId) {
1510 if (userId == UserHandle.getCallingUserId()) {
1511 // Not a cross-user call.
1512 return;
1513 }
1514 mContext.enforceCallingOrSelfPermission(
1515 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1516 "ConnectivityService");
1517 }
1518
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001519 private void enforceInternetPermission() {
1520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.INTERNET,
1522 "ConnectivityService");
1523 }
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001526 mContext.enforceCallingOrSelfPermission(
1527 android.Manifest.permission.ACCESS_NETWORK_STATE,
1528 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530
1531 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001532 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534
Charles He36738632017-05-15 17:07:18 +01001535 private void enforceSettingsPermission() {
1536 mContext.enforceCallingOrSelfPermission(
1537 android.Manifest.permission.NETWORK_SETTINGS,
1538 "ConnectivityService");
1539 }
1540
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001541 private void enforceTetherAccessPermission() {
1542 mContext.enforceCallingOrSelfPermission(
1543 android.Manifest.permission.ACCESS_NETWORK_STATE,
1544 "ConnectivityService");
1545 }
1546
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001547 private void enforceConnectivityInternalPermission() {
1548 mContext.enforceCallingOrSelfPermission(
1549 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1550 "ConnectivityService");
1551 }
1552
Hugo Benichi514da602016-07-19 15:59:27 +09001553 private void enforceConnectivityRestrictedNetworksPermission() {
1554 try {
1555 mContext.enforceCallingOrSelfPermission(
1556 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1557 "ConnectivityService");
1558 return;
1559 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1560 enforceConnectivityInternalPermission();
1561 }
1562
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001563 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001564 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001565 }
1566
Lorenzo Colitti18660282016-07-04 12:55:44 +09001567 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001568 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001569 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001570 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001571 }
1572
1573 private void sendInetConditionBroadcast(NetworkInfo info) {
1574 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1575 }
1576
Wink Saville628b0852011-08-04 15:01:58 -07001577 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001578 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001579 info = new NetworkInfo(info);
1580 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001581 }
1582
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001583 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001584 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001585 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (info.isFailover()) {
1587 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1588 info.setFailover(false);
1589 }
1590 if (info.getReason() != null) {
1591 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1592 }
1593 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001594 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1595 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001597 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001598 return intent;
1599 }
1600
1601 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1602 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1603 }
1604
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001605 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001606 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1607 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1608 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001609 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001610 final long ident = Binder.clearCallingIdentity();
1611 try {
1612 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1613 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1614 } finally {
1615 Binder.restoreCallingIdentity(ident);
1616 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001617 }
1618
Mike Lockwood0f79b542009-08-14 14:18:49 -04001619 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001620 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001621 if (!mSystemReady) {
1622 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001623 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001624 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001625 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001626 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001627 }
1628
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001629 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001630 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001631 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001632 final NetworkInfo ni = intent.getParcelableExtra(
1633 ConnectivityManager.EXTRA_NETWORK_INFO);
1634 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1635 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1636 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001637 } else {
1638 BroadcastOptions opts = BroadcastOptions.makeBasic();
1639 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1640 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001641 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001642 final IBatteryStats bs = BatteryStatsService.getService();
1643 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001644 bs.noteConnectivityChanged(intent.getIntExtra(
1645 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1646 ni != null ? ni.getState().toString() : "?");
1647 } catch (RemoteException e) {
1648 }
1649 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001650 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001651 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001652 } finally {
1653 Binder.restoreCallingIdentity(ident);
1654 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001655 }
1656 }
1657
1658 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001659 loadGlobalProxy();
1660
Hugo Benichi20035e02017-04-26 14:53:28 +09001661 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001662 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001663 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001664 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001665 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001666 }
1667 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001668 // load the global proxy at startup
1669 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001670
Robin Lee244ce8e2016-01-05 18:03:46 +00001671 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1672 // for user to unlock device too.
1673 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001674
Erik Klineda4bfa82015-04-30 12:58:40 +09001675 // Configure whether mobile data is always on.
1676 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1677
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001678 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001679
1680 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001685 *
1686 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001687 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001688 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001689 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1690 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001691
1692 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001693 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001694
Robert Greenwalt7b816022014-04-18 15:25:25 -07001695 if (networkAgent.networkCapabilities.hasTransport(
1696 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001697 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1698 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001699 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001700 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001701 } else if (networkAgent.networkCapabilities.hasTransport(
1702 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001703 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1704 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001705 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001706 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001707 } else {
1708 // do not track any other networks
1709 timeout = 0;
1710 }
1711
Robert Greenwalt7b816022014-04-18 15:25:25 -07001712 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001713 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001714 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001715 } catch (Exception e) {
1716 // You shall not crash!
1717 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001718 }
1719 }
1720 }
1721
1722 /**
1723 * Remove data activity tracking when network disconnects.
1724 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001725 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1726 final String iface = networkAgent.linkProperties.getInterfaceName();
1727 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001728
Robert Greenwalt7b816022014-04-18 15:25:25 -07001729 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1730 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001731 try {
1732 // the call fails silently if no idletimer setup for this interface
1733 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001734 } catch (Exception e) {
1735 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001736 }
1737 }
1738 }
1739
1740 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001741 * Reads the network specific MTU size from reources.
1742 * and set it on it's iface.
1743 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1745 final String iface = newLp.getInterfaceName();
1746 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001747 if (oldLp == null && mtu == 0) {
1748 // Silently ignore unset MTU value.
1749 return;
1750 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1752 if (VDBG) log("identical MTU - not setting");
1753 return;
1754 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001755 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001756 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 return;
1758 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001759
w1997615afd812014-08-05 15:18:11 -07001760 // Cannot set MTU without interface name
1761 if (TextUtils.isEmpty(iface)) {
1762 loge("Setting MTU size with null iface.");
1763 return;
1764 }
1765
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001767 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001768 mNetd.setMtu(iface, mtu);
1769 } catch (Exception e) {
1770 Slog.e(TAG, "exception in setMtu()" + e);
1771 }
1772 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001773
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001774 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001775 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1776
1777 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001778 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001779 protected MockableSystemProperties getSystemProperties() {
1780 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001781 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001782
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001783 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1784 if (isDefaultNetwork(nai) == false) {
1785 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001786 }
1787
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001788 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1789 String[] values = null;
1790 if (tcpBufferSizes != null) {
1791 values = tcpBufferSizes.split(",");
1792 }
1793
1794 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001795 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001796 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1797 values = tcpBufferSizes.split(",");
1798 }
1799
1800 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1801
1802 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001803 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001804
1805 final String prefix = "/sys/kernel/ipv4/tcp_";
1806 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1807 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1808 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1809 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1810 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1811 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1812 mCurrentTcpBufferSizes = tcpBufferSizes;
1813 } catch (IOException e) {
1814 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001815 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001816
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001817 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001818 Settings.Global.TCP_DEFAULT_INIT_RWND,
1819 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001820 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1821 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001822 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001823 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001824 }
1825
Mattias Falk8b47b362011-08-23 14:15:13 +02001826 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001827 /*
1828 * Tell the VMs to toss their DNS caches
1829 */
1830 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1831 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001832 /*
1833 * Connectivity events can happen before boot has completed ...
1834 */
1835 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001836 final long ident = Binder.clearCallingIdentity();
1837 try {
1838 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1839 } finally {
1840 Binder.restoreCallingIdentity(ident);
1841 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001842 }
1843
Robert Greenwalt562cc542014-05-15 18:07:26 -07001844 @Override
1845 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001846 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001847 NETWORK_RESTORE_DELAY_PROP_NAME);
1848 if(restoreDefaultNetworkDelayStr != null &&
1849 restoreDefaultNetworkDelayStr.length() != 0) {
1850 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001851 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001852 } catch (NumberFormatException e) {
1853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001855 // if the system property isn't set, use the value for the apn type
1856 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1857
1858 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1859 (mNetConfigs[networkType] != null)) {
1860 ret = mNetConfigs[networkType].restoreTime;
1861 }
1862 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001865 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001866 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001867 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001868 }
1869 return false;
1870 }
1871
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001872 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1873 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1874 final long DIAG_TIME_MS = 5000;
1875 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1876 // Start gathering diagnostic information.
1877 netDiags.add(new NetworkDiagnostics(
1878 nai.network,
1879 new LinkProperties(nai.linkProperties), // Must be a copy.
1880 DIAG_TIME_MS));
1881 }
1882
1883 for (NetworkDiagnostics netDiag : netDiags) {
1884 pw.println();
1885 netDiag.waitForMeasurements();
1886 netDiag.dump(pw);
1887 }
1888 }
1889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001891 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001892 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1893 }
1894
1895 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001896 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001897 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001898 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001899
Erik Kline7747fd42017-05-12 16:52:48 +09001900 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001901 dumpNetworkDiagnostics(pw);
1902 return;
Erik Klineee363c42017-05-29 09:11:03 +09001903 } else if (argsContain(args, TETHERING_ARG)) {
1904 mTethering.dump(fd, pw, args);
1905 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001906 }
Erik Kline379747a2015-06-05 17:47:34 +09001907
Lorenzo Colittie3805462015-06-03 11:18:24 +09001908 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001909 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001910 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001911 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001912 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001913 pw.println();
1914
Paul Jensen85cf78e2015-06-25 13:25:07 -04001915 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001916 pw.print("Active default network: ");
1917 if (defaultNai == null) {
1918 pw.println("none");
1919 } else {
1920 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001922 pw.println();
1923
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001924 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001925 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1927 pw.println(nai.toString());
1928 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001929 pw.println(String.format(
1930 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1931 nai.numForegroundNetworkRequests(),
1932 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1933 nai.numBackgroundNetworkRequests(),
1934 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001935 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001936 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1937 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001938 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001939 pw.decreaseIndent();
1940 pw.println("Lingered:");
1941 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001942 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001943 pw.decreaseIndent();
1944 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001945 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001946 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001947 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001948
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001949 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001950 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001951 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1952 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001953 }
1954 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001956
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001957 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001958
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001959 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001960 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001961
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001962 pw.println();
1963 mKeepaliveTracker.dump(pw);
1964
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001965 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001966 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001967
Erik Kline7747fd42017-05-12 16:52:48 +09001968 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001969 pw.println();
1970 synchronized (mValidationLogs) {
1971 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001972 for (ValidationLog p : mValidationLogs) {
1973 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001974 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001975 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001976 pw.decreaseIndent();
1977 }
1978 }
Erik Kline7523eb32015-07-09 18:24:03 +09001979
1980 pw.println();
1981 pw.println("mNetworkRequestInfoLogs (most recent first):");
1982 pw.increaseIndent();
1983 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1984 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001985
1986 pw.println();
1987 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1988 pw.increaseIndent();
1989 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1990 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001991
1992 pw.println();
1993 pw.println("NetTransition WakeLock activity (most recent first):");
1994 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09001995 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1996 pw.println("total releases: " + mTotalWakelockReleases);
1997 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1998 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1999 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2000 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2001 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2002 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002003 mWakelockLogs.reverseDump(fd, pw, args);
2004 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 }
2007
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002008 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002009 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002010 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002011 if (officialNai != null && officialNai.equals(nai)) return true;
2012 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002013 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002014 " - " + nai);
2015 }
2016 return false;
2017 }
2018
Robert Greenwalt42acef32009-08-12 16:08:25 -07002019 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002020 private class NetworkStateTrackerHandler extends Handler {
2021 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002022 super(looper);
2023 }
2024
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002025 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002027 default:
2028 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002029 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002030 handleAsyncChannelHalfConnect(msg);
2031 break;
2032 }
2033 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2034 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2035 if (nai != null) nai.asyncChannel.disconnect();
2036 break;
2037 }
2038 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2039 handleAsyncChannelDisconnected(msg);
2040 break;
2041 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002042 }
2043 return true;
2044 }
2045
2046 private void maybeHandleNetworkAgentMessage(Message msg) {
2047 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2048 if (nai == null) {
2049 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002050 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002051 }
2052 return;
2053 }
2054
2055 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002056 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002057 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2058 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002059 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2060 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002061 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002062 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002063 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002064 break;
2065 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002067 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002068 break;
2069 }
2070 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002071 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 updateNetworkInfo(nai, info);
2073 break;
2074 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002075 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002076 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002077 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002078 break;
2079 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002080 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002081 try {
2082 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002083 } catch (Exception e) {
2084 // Never crash!
2085 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002086 }
2087 break;
2088 }
2089 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002090 try {
2091 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002092 } catch (Exception e) {
2093 // Never crash!
2094 loge("Exception in removeVpnUidRanges: " + e);
2095 }
2096 break;
2097 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002098 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002099 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2100 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002101 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002102 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002103 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002104 break;
2105 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002106 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002107 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2108 break;
2109 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002110 }
2111 }
2112
2113 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2114 switch (msg.what) {
2115 default:
2116 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002117 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002118 final NetworkAgentInfo nai;
2119 synchronized (mNetworkForNetId) {
2120 nai = mNetworkForNetId.get(msg.arg2);
2121 }
2122 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002123 final boolean valid =
2124 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002125 final boolean wasValidated = nai.lastValidated;
Hugo Benichi380a0632017-10-20 09:25:29 +09002126 final boolean wasDefault = isDefaultNetwork(nai);
Paul Jensen232437312016-04-06 09:51:26 -04002127 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2128 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002129 if (valid != nai.lastValidated) {
Hugo Benichi380a0632017-10-20 09:25:29 +09002130 if (wasDefault) {
2131 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2132 SystemClock.elapsedRealtime(), valid);
2133 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04002134 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002135 nai.lastValidated = valid;
2136 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002137 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002138 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2139 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002140 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002141 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002142 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002143 Bundle redirectUrlBundle = new Bundle();
2144 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002145 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002146 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002147 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002148 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002149 if (wasValidated && !nai.lastValidated) {
2150 handleNetworkUnvalidated(nai);
2151 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002152 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002153 break;
2154 }
Paul Jensen869868be2014-05-15 10:33:05 -04002155 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002156 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002157 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002158 final NetworkAgentInfo nai;
2159 synchronized (mNetworkForNetId) {
2160 nai = mNetworkForNetId.get(netId);
2161 }
Calvin Onbe96da12016-10-11 15:10:46 -07002162 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002163 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002164 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002165 nai.lastCaptivePortalDetected = visible;
2166 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002167 if (nai.lastCaptivePortalDetected &&
2168 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2169 if (DBG) log("Avoiding captive portal network: " + nai.name());
2170 nai.asyncChannel.sendMessage(
2171 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2172 teardownUnneededNetwork(nai);
2173 break;
2174 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002175 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002176 }
2177 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002178 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002179 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002180 if (nai == null) {
2181 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2182 break;
2183 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002184 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002185 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002186 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002187 }
Paul Jensen869868be2014-05-15 10:33:05 -04002188 }
Paul Jensen869868be2014-05-15 10:33:05 -04002189 break;
2190 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002191 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002192 return true;
2193 }
2194
Calvin Onbe96da12016-10-11 15:10:46 -07002195 private int getCaptivePortalMode() {
2196 return Settings.Global.getInt(mContext.getContentResolver(),
2197 Settings.Global.CAPTIVE_PORTAL_MODE,
2198 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2199 }
2200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002201 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2202 switch (msg.what) {
2203 default:
2204 return false;
2205 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2206 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2207 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2208 handleLingerComplete(nai);
2209 }
2210 break;
2211 }
2212 }
2213 return true;
2214 }
2215
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002216 @Override
2217 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002218 if (!maybeHandleAsyncChannelMessage(msg) &&
2219 !maybeHandleNetworkMonitorMessage(msg) &&
2220 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002221 maybeHandleNetworkAgentMessage(msg);
2222 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002223 }
2224 }
2225
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002226 private void updateLingerState(NetworkAgentInfo nai, long now) {
2227 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2228 // 2. If the network was lingering and there are now requests, unlinger it.
2229 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2230 // one lingered request, start lingering.
2231 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002232 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002233 if (DBG) log("Unlingering " + nai.name());
2234 nai.unlinger();
2235 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002236 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002237 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002238 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002239 nai.linger();
2240 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2241 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2242 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002243 }
2244
Robert Greenwalt7b816022014-04-18 15:25:25 -07002245 private void handleAsyncChannelHalfConnect(Message msg) {
2246 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002247 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2249 if (VDBG) log("NetworkFactory connected");
2250 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002251 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002252 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002253 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002254 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002255 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002256 }
2257 } else {
2258 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002259 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002260 }
2261 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2262 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2263 if (VDBG) log("NetworkAgent connected");
2264 // A network agent has requested a connection. Establish the connection.
2265 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2266 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2267 } else {
2268 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002269 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002270 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002271 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002272 synchronized (mNetworkForNetId) {
2273 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002274 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002275 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002276 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002277 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002278 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002279 }
2280 }
2281 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002282
Robert Greenwalt7b816022014-04-18 15:25:25 -07002283 private void handleAsyncChannelDisconnected(Message msg) {
2284 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2285 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002286 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002287 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002288 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002289 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002290 // TODO - if we move the logic to the network agent (have them disconnect
2291 // because they lost all their requests or because their score isn't good)
2292 // then they would disconnect organically, report their new state and then
2293 // disconnect the channel.
2294 if (nai.networkInfo.isConnected()) {
2295 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2296 null, null);
2297 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002298 final boolean wasDefault = isDefaultNetwork(nai);
2299 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002300 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002301 // Log default network disconnection before required book-keeping.
2302 // Let rematchAllNetworksAndRequests() below record a new default network event
2303 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2304 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002305 long now = SystemClock.elapsedRealtime();
2306 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002307 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002308 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002309 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2310 // by other networks that are already connected. Perhaps that can be done by
2311 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2312 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002313 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002314 mKeepaliveTracker.handleStopAllKeepalives(nai,
2315 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002316 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2317 // Disable wakeup packet monitoring for each interface.
2318 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2319 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002320 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002321 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002322 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002323 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002324 // Remove the NetworkAgent, but don't mark the netId as
2325 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002326 mNetworkForNetId.remove(nai.network.netId);
2327 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002328 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002329 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2330 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002331 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002332 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002333 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002334 sendUpdatedScoreToFactories(request, 0);
2335 }
2336 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002337 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002338 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002339 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002340 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002341 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002343 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002344 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002345 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002346 if (nai.created) {
2347 // Tell netd to clean up the configuration for this network
2348 // (routing rules, DNS, etc).
2349 // This may be slow as it requires a lot of netd shelling out to ip and
2350 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2351 // after we've rematched networks with requests which should make a potential
2352 // fallback network the default or requested a new network from the
2353 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2354 // long time.
2355 try {
2356 mNetd.removeNetwork(nai.network.netId);
2357 } catch (Exception e) {
2358 loge("Exception removing network: " + e);
2359 }
2360 }
2361 synchronized (mNetworkForNetId) {
2362 mNetIdInUse.delete(nai.network.netId);
2363 }
2364 } else {
2365 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2366 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002367 }
2368 }
2369
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002370 // If this method proves to be too slow then we can maintain a separate
2371 // pendingIntent => NetworkRequestInfo map.
2372 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2373 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2374 Intent intent = pendingIntent.getIntent();
2375 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2376 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2377 if (existingPendingIntent != null &&
2378 existingPendingIntent.getIntent().filterEquals(intent)) {
2379 return entry.getValue();
2380 }
2381 }
2382 return null;
2383 }
2384
2385 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2386 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2387
2388 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2389 if (existingRequest != null) { // remove the existing request.
2390 if (DBG) log("Replacing " + existingRequest.request + " with "
2391 + nri.request + " because their intents matched.");
2392 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2393 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002394 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002395 }
2396
Erik Klineda4bfa82015-04-30 12:58:40 +09002397 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002398 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002399 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002400 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002401 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002402 if (nri.request.networkCapabilities.hasSignalStrength() &&
2403 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2404 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002405 }
2406 }
2407 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002408 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002409 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002410 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002411 }
2412 }
2413
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002414 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2415 int callingUid) {
2416 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2417 if (nri != null) {
2418 handleReleaseNetworkRequest(nri.request, callingUid);
2419 }
2420 }
2421
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002422 // Determines whether the network is the best (or could become the best, if it validated), for
2423 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2424 // on the value of reason:
2425 //
2426 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2427 // then it should be torn down.
2428 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2429 // then it should be lingered.
2430 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2431 final int numRequests;
2432 switch (reason) {
2433 case TEARDOWN:
2434 numRequests = nai.numRequestNetworkRequests();
2435 break;
2436 case LINGER:
2437 numRequests = nai.numForegroundNetworkRequests();
2438 break;
2439 default:
2440 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2441 return true;
2442 }
2443
2444 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002445 return false;
2446 }
Paul Jensene0988542015-06-25 15:30:08 -04002447 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002448 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2449 // Background requests don't affect lingering.
2450 continue;
2451 }
2452
Paul Jensene0988542015-06-25 15:30:08 -04002453 // If this Network is already the highest scoring Network for a request, or if
2454 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002455 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002456 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002457 // Note that this catches two important cases:
2458 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2459 // is currently satisfying the request. This is desirable when
2460 // cellular ends up validating but WiFi does not.
2461 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002462 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002463 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002464 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002465 nai.getCurrentScoreAsValidated())) {
2466 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002467 }
2468 }
Paul Jensene0988542015-06-25 15:30:08 -04002469 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002470 }
2471
Erik Klineacdd6392016-07-07 16:50:58 +09002472 private NetworkRequestInfo getNriForAppRequest(
2473 NetworkRequest request, int callingUid, String requestedOperation) {
2474 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2475
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002477 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002478 log(String.format("UID %d attempted to %s for unowned request %s",
2479 callingUid, requestedOperation, nri));
2480 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002481 }
Erik Klineacdd6392016-07-07 16:50:58 +09002482 }
2483
2484 return nri;
2485 }
2486
Erik Kline57faba92015-11-25 12:49:38 +09002487 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002488 if (mNetworkRequests.get(nri.request) == null) {
2489 return;
Erik Kline57faba92015-11-25 12:49:38 +09002490 }
Hugo Benichicd952782017-09-20 11:20:14 +09002491 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002492 return;
2493 }
2494 if (VDBG || (DBG && nri.request.isRequest())) {
2495 log("releasing " + nri.request + " (timeout)");
2496 }
2497 handleRemoveNetworkRequest(nri);
2498 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002499 }
2500
Erik Klineacdd6392016-07-07 16:50:58 +09002501 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002502 final NetworkRequestInfo nri =
2503 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2504 if (nri == null) {
2505 return;
Erik Kline57faba92015-11-25 12:49:38 +09002506 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002507 if (VDBG || (DBG && nri.request.isRequest())) {
2508 log("releasing " + nri.request + " (release request)");
2509 }
2510 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002511 }
Erik Klineacdd6392016-07-07 16:50:58 +09002512
Hugo Benichidba33db2017-03-23 22:40:44 +09002513 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002514 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002515 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002516 synchronized (mUidToNetworkRequestCount) {
2517 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2518 if (requests < 1) {
2519 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2520 nri.mUid);
2521 } else if (requests == 1) {
2522 mUidToNetworkRequestCount.removeAt(
2523 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2524 } else {
2525 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2526 }
2527 }
2528 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2529 if (nri.request.isRequest()) {
2530 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002531 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002532 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002533 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002534 nai.removeRequest(nri.request.requestId);
2535 if (VDBG) {
2536 log(" Removing from current network " + nai.name() +
2537 ", leaving " + nai.numNetworkRequests() + " requests.");
2538 }
2539 // If there are still lingered requests on this network, don't tear it down,
2540 // but resume lingering instead.
2541 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002542 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002543 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2544 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002545 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002546 wasKept = true;
2547 }
Hugo Benichicd952782017-09-20 11:20:14 +09002548 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002549 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2550 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002551 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002552 }
Erik Klineacdd6392016-07-07 16:50:58 +09002553 }
2554
2555 // TODO: remove this code once we know that the Slog.wtf is never hit.
2556 //
2557 // Find all networks that are satisfying this request and remove the request
2558 // from their request lists.
2559 // TODO - it's my understanding that for a request there is only a single
2560 // network satisfying it, so this loop is wasteful
2561 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2562 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2563 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2564 otherNai.name() + ", but mNetworkAgentInfos says " +
2565 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002566 }
2567 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002568
Erik Klineacdd6392016-07-07 16:50:58 +09002569 // Maintain the illusion. When this request arrived, we might have pretended
2570 // that a network connected to serve it, even though the network was already
2571 // connected. Now that this request has gone away, we might have to pretend
2572 // that the network disconnected. LegacyTypeTracker will generate that
2573 // phantom disconnect for this type.
2574 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2575 boolean doRemove = true;
2576 if (wasKept) {
2577 // check if any of the remaining requests for this network are for the
2578 // same legacy type - if so, don't remove the nai
2579 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2580 NetworkRequest otherRequest = nai.requestAt(i);
2581 if (otherRequest.legacyType == nri.request.legacyType &&
2582 otherRequest.isRequest()) {
2583 if (DBG) log(" still have other legacy request - leaving");
2584 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002585 }
2586 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002587 }
2588
Erik Klineacdd6392016-07-07 16:50:58 +09002589 if (doRemove) {
2590 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002591 }
2592 }
Erik Klineacdd6392016-07-07 16:50:58 +09002593
2594 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2595 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2596 nri.request);
2597 }
2598 } else {
2599 // listens don't have a singular affectedNetwork. Check all networks to see
2600 // if this listen request applies and remove it.
2601 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2602 nai.removeRequest(nri.request.requestId);
2603 if (nri.request.networkCapabilities.hasSignalStrength() &&
2604 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2605 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2606 }
2607 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002608 }
2609 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002610
Lorenzo Colitti18660282016-07-04 12:55:44 +09002611 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002612 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2613 enforceConnectivityInternalPermission();
2614 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002615 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002616 }
2617
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002618 @Override
2619 public void setAvoidUnvalidated(Network network) {
2620 enforceConnectivityInternalPermission();
2621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2622 }
2623
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002624 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2625 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2626 " accept=" + accept + " always=" + always);
2627
2628 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2629 if (nai == null) {
2630 // Nothing to do.
2631 return;
2632 }
2633
2634 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002635 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002636 return;
2637 }
2638
2639 if (!nai.networkMisc.explicitlySelected) {
2640 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2641 }
2642
2643 if (accept != nai.networkMisc.acceptUnvalidated) {
2644 int oldScore = nai.getCurrentScore();
2645 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002646 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002647 sendUpdatedScoreToFactories(nai);
2648 }
2649
2650 if (always) {
2651 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002652 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002653 }
2654
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002655 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002656 // Tell the NetworkAgent to not automatically reconnect to the network.
2657 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2658 // Teardown the nework.
2659 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002660 }
2661
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002662 }
2663
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002664 private void handleSetAvoidUnvalidated(Network network) {
2665 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2666 if (nai == null || nai.lastValidated) {
2667 // Nothing to do. The network either disconnected or revalidated.
2668 return;
2669 }
2670 if (!nai.avoidUnvalidated) {
2671 int oldScore = nai.getCurrentScore();
2672 nai.avoidUnvalidated = true;
2673 rematchAllNetworksAndRequests(nai, oldScore);
2674 sendUpdatedScoreToFactories(nai);
2675 }
2676 }
2677
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002678 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002679 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002680 mHandler.sendMessageDelayed(
2681 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2682 PROMPT_UNVALIDATED_DELAY_MS);
2683 }
2684
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002685 @Override
2686 public void startCaptivePortalApp(Network network) {
2687 enforceConnectivityInternalPermission();
2688 mHandler.post(() -> {
2689 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2690 if (nai == null) return;
2691 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2692 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2693 });
2694 }
2695
Hugo Benichic8e9e122016-09-14 23:23:08 +00002696 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002697 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002698 }
2699
Erik Kline065ab6e2016-10-02 18:02:14 +09002700 private void rematchForAvoidBadWifiUpdate() {
2701 rematchAllNetworksAndRequests(null, 0);
2702 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2703 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2704 sendUpdatedScoreToFactories(nai);
2705 }
2706 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002707 }
2708
Erik Kline065ab6e2016-10-02 18:02:14 +09002709 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002710 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002711 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002712 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002713 if (!configRestrict) {
2714 pw.println("Bad Wi-Fi avoidance: unrestricted");
2715 return;
2716 }
2717
2718 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2719 pw.increaseIndent();
2720 pw.println("Config restrict: " + configRestrict);
2721
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002722 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002723 String description;
2724 // Can't use a switch statement because strings are legal case labels, but null is not.
2725 if ("0".equals(value)) {
2726 description = "get stuck";
2727 } else if (value == null) {
2728 description = "prompt";
2729 } else if ("1".equals(value)) {
2730 description = "avoid";
2731 } else {
2732 description = value + " (?)";
2733 }
2734 pw.println("User setting: " + description);
2735 pw.println("Network overrides:");
2736 pw.increaseIndent();
2737 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2738 if (nai.avoidUnvalidated) {
2739 pw.println(nai.name());
2740 }
2741 }
2742 pw.decreaseIndent();
2743 pw.decreaseIndent();
2744 }
2745
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002746 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2747 final String action;
2748 switch (type) {
2749 case NO_INTERNET:
2750 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2751 break;
2752 case LOST_INTERNET:
2753 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2754 break;
2755 default:
2756 Slog.wtf(TAG, "Unknown notification type " + type);
2757 return;
2758 }
2759
2760 Intent intent = new Intent(action);
2761 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2762 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2763 intent.setClassName("com.android.settings",
2764 "com.android.settings.wifi.WifiNoInternetDialog");
2765
2766 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2767 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2768 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2769 }
2770
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002771 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002772 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002773 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2774
2775 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2776 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002777 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002778 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002779 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2780 return;
2781 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002782 showValidationNotification(nai, NotificationType.NO_INTERNET);
2783 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002785 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2786 NetworkCapabilities nc = nai.networkCapabilities;
2787 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002788
Erik Kline065ab6e2016-10-02 18:02:14 +09002789 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002790 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002791 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2792 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002793 }
2794
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002795 @Override
2796 public int getMultipathPreference(Network network) {
2797 enforceAccessPermission();
2798
2799 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002800 if (nai != null && nai.networkCapabilities
2801 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002802 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2803 }
2804
2805 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2806 }
2807
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002808 private class InternalHandler extends Handler {
2809 public InternalHandler(Looper looper) {
2810 super(looper);
2811 }
2812
2813 @Override
2814 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002815 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002816 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002817 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002818 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002819 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002820 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002821 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002823 break;
2824 }
Jason Monkdecd2952013-10-10 14:02:51 -04002825 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002826 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002827 break;
2828 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002829 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002830 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2831 break;
2832 }
2833 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2834 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002835 break;
2836 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002837 case EVENT_REGISTER_NETWORK_AGENT: {
2838 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2839 break;
2840 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002841 case EVENT_REGISTER_NETWORK_REQUEST:
2842 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002843 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002844 break;
2845 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002846 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2847 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002848 handleRegisterNetworkRequestWithIntent(msg);
2849 break;
2850 }
Erik Kline57faba92015-11-25 12:49:38 +09002851 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2852 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2853 handleTimedOutNetworkRequest(nri);
2854 break;
2855 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002856 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2857 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2858 break;
2859 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002860 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002861 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002862 break;
2863 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002864 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002865 Network network = (Network) msg.obj;
2866 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002867 break;
2868 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002869 case EVENT_SET_AVOID_UNVALIDATED: {
2870 handleSetAvoidUnvalidated((Network) msg.obj);
2871 break;
2872 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002873 case EVENT_PROMPT_UNVALIDATED: {
2874 handlePromptUnvalidated((Network) msg.obj);
2875 break;
2876 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002877 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2878 handleMobileDataAlwaysOn();
2879 break;
2880 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002881 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2882 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2883 mKeepaliveTracker.handleStartKeepalive(msg);
2884 break;
2885 }
2886 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2887 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2888 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2889 int slot = msg.arg1;
2890 int reason = msg.arg2;
2891 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2892 break;
2893 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002894 case EVENT_SYSTEM_READY: {
2895 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2896 nai.networkMonitor.systemReady = true;
2897 }
2898 break;
2899 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002900 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002901 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002902 break;
2903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905 }
2906 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002907
2908 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002909 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002910 public int tether(String iface, String callerPkg) {
2911 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002912 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002913 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002914 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002915 } else {
2916 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2917 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002918 }
2919
2920 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002921 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002922 public int untether(String iface, String callerPkg) {
2923 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002924
2925 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002926 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002927 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002928 } else {
2929 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2930 }
2931 }
2932
2933 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002934 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002935 public int getLastTetherError(String iface) {
2936 enforceTetherAccessPermission();
2937
2938 if (isTetheringSupported()) {
2939 return mTethering.getLastTetherError(iface);
2940 } else {
2941 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2942 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002943 }
2944
2945 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002947 public String[] getTetherableUsbRegexs() {
2948 enforceTetherAccessPermission();
2949 if (isTetheringSupported()) {
2950 return mTethering.getTetherableUsbRegexs();
2951 } else {
2952 return new String[0];
2953 }
2954 }
2955
Lorenzo Colitti18660282016-07-04 12:55:44 +09002956 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002957 public String[] getTetherableWifiRegexs() {
2958 enforceTetherAccessPermission();
2959 if (isTetheringSupported()) {
2960 return mTethering.getTetherableWifiRegexs();
2961 } else {
2962 return new String[0];
2963 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002964 }
2965
Lorenzo Colitti18660282016-07-04 12:55:44 +09002966 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002967 public String[] getTetherableBluetoothRegexs() {
2968 enforceTetherAccessPermission();
2969 if (isTetheringSupported()) {
2970 return mTethering.getTetherableBluetoothRegexs();
2971 } else {
2972 return new String[0];
2973 }
2974 }
2975
Lorenzo Colitti18660282016-07-04 12:55:44 +09002976 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002977 public int setUsbTethering(boolean enable, String callerPkg) {
2978 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002979 if (isTetheringSupported()) {
2980 return mTethering.setUsbTethering(enable);
2981 } else {
2982 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2983 }
2984 }
2985
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002986 // TODO - move iface listing, queries, etc to new module
2987 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002988 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002989 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002990 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002991 return mTethering.getTetherableIfaces();
2992 }
2993
Lorenzo Colitti18660282016-07-04 12:55:44 +09002994 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002995 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002996 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002997 return mTethering.getTetheredIfaces();
2998 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002999
Lorenzo Colitti18660282016-07-04 12:55:44 +09003000 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003001 public String[] getTetheringErroredIfaces() {
3002 enforceTetherAccessPermission();
3003 return mTethering.getErroredIfaces();
3004 }
3005
Lorenzo Colitti18660282016-07-04 12:55:44 +09003006 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003007 public String[] getTetheredDhcpRanges() {
3008 enforceConnectivityInternalPermission();
3009 return mTethering.getTetheredDhcpRanges();
3010 }
3011
Udam Saini0e94c362017-06-07 12:06:28 -07003012 @Override
3013 public boolean isTetheringSupported(String callerPkg) {
3014 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3015 return isTetheringSupported();
3016 }
3017
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003018 // if ro.tether.denied = true we default to no tethering
3019 // gservices could set the secure setting to 1 though to enable it on a build where it
3020 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003021 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003022 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3023 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3024 Settings.Global.TETHER_SUPPORTED, defaultVal));
3025 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003026 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003027
3028 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3029 boolean adminUser = false;
3030 final long token = Binder.clearCallingIdentity();
3031 try {
3032 adminUser = mUserManager.isAdminUser();
3033 } finally {
3034 Binder.restoreCallingIdentity(token);
3035 }
3036
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003037 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003038 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003039
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003040 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003041 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3042 String callerPkg) {
3043 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003044 if (!isTetheringSupported()) {
3045 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3046 return;
3047 }
3048 mTethering.startTethering(type, receiver, showProvisioningUi);
3049 }
3050
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003051 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003052 public void stopTethering(int type, String callerPkg) {
3053 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003054 mTethering.stopTethering(type);
3055 }
3056
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003057 // Called when we lose the default network and have no replacement yet.
3058 // This will automatically be cleared after X seconds or a new default network
3059 // becomes CONNECTED, whichever happens first. The timer is started by the
3060 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003061 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003062 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003063 if (mNetTransitionWakeLock.isHeld()) {
3064 return;
3065 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003066 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003067 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3068 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003069 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003070 mWakelockLogs.log("ACQUIRE for " + forWhom);
3071 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3072 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003073 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003074
Hugo Benichi4c31b342017-03-30 23:18:10 +09003075 // Called when we gain a new default network to release the network transition wakelock in a
3076 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3077 // message is cancelled.
3078 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003079 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003080 if (!mNetTransitionWakeLock.isHeld()) {
3081 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003082 }
3083 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003084 // Cancel self timeout on wakelock hold.
3085 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3086 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3087 mHandler.sendMessageDelayed(msg, 1000);
3088 }
3089
3090 // Called when either message of ensureNetworkTransitionWakelock or
3091 // scheduleReleaseNetworkTransitionWakelock is processed.
3092 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3093 String event = eventName(eventId);
3094 synchronized (this) {
3095 if (!mNetTransitionWakeLock.isHeld()) {
3096 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3097 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3098 return;
3099 }
3100 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003101 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3102 mTotalWakelockDurationMs += lockDuration;
3103 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3104 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003105 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003106 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003107 }
3108
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003109 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003110 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003111 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003112 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003113 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003114 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003115 }
3116
Lorenzo Colitti18660282016-07-04 12:55:44 +09003117 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003118 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003119 enforceAccessPermission();
3120 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003121 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003122 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003123 mHandler.sendMessage(
3124 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3125 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003126
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003127 private void handleReportNetworkConnectivity(
3128 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003129 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003130 if (network == null) {
3131 nai = getDefaultNetwork();
3132 } else {
3133 nai = getNetworkAgentInfoForNetwork(network);
3134 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003135 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3136 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3137 return;
3138 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003139 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003140 if (hasConnectivity == nai.lastValidated) {
3141 return;
3142 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003143 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003144 int netid = nai.network.netId;
3145 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003146 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003147 // Validating a network that has not yet connected could result in a call to
3148 // rematchNetworkAndRequests() which is not meant to work on such networks.
3149 if (!nai.everConnected) {
3150 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003151 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003152 LinkProperties lp = getLinkProperties(nai);
3153 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3154 return;
3155 }
3156 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003157 }
3158
Paul Jensencee9b512015-05-06 07:32:40 -04003159 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003160 // this information is already available as a world read/writable jvm property
3161 // so this API change wouldn't have a benifit. It also breaks the passing
3162 // of proxy info to all the JVMs.
3163 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003164 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003165 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003166 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3167 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003168 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003169 }
3170
Lorenzo Colitti18660282016-07-04 12:55:44 +09003171 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003172 public ProxyInfo getProxyForNetwork(Network network) {
3173 if (network == null) return getDefaultProxy();
3174 final ProxyInfo globalProxy = getGlobalProxy();
3175 if (globalProxy != null) return globalProxy;
3176 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3177 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3178 // caller may not have.
3179 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3180 if (nai == null) return null;
3181 synchronized (nai) {
3182 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3183 if (proxyInfo == null) return null;
3184 return new ProxyInfo(proxyInfo);
3185 }
3186 }
3187
Paul Jensene0bef712014-12-10 15:12:18 -05003188 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3189 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3190 // proxy is null then there is no proxy in place).
3191 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3192 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3193 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3194 proxy = null;
3195 }
3196 return proxy;
3197 }
3198
3199 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3200 // better for determining if a new proxy broadcast is necessary:
3201 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3202 // avoid unnecessary broadcasts.
3203 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3204 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3205 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3206 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3207 // all set.
3208 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3209 a = canonicalizeProxyInfo(a);
3210 b = canonicalizeProxyInfo(b);
3211 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3212 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3213 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3214 }
3215
Jason Monk207900c2014-04-25 15:00:09 -04003216 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003217 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003218
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003219 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003220 if (proxyProperties == mGlobalProxy) return;
3221 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3222 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3223
3224 String host = "";
3225 int port = 0;
3226 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003227 String pacFileUrl = "";
3228 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003229 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003230 if (!proxyProperties.isValid()) {
3231 if (DBG)
3232 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3233 return;
3234 }
Jason Monk207900c2014-04-25 15:00:09 -04003235 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003236 host = mGlobalProxy.getHost();
3237 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003238 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003239 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003240 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003241 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003242 } else {
3243 mGlobalProxy = null;
3244 }
3245 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003246 final long token = Binder.clearCallingIdentity();
3247 try {
3248 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3249 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3250 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3251 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003252 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003253 } finally {
3254 Binder.restoreCallingIdentity(token);
3255 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003256
Jason Monkcf0f97a2014-10-02 15:39:38 -04003257 if (mGlobalProxy == null) {
3258 proxyProperties = mDefaultProxy;
3259 }
3260 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003262 }
3263
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003264 private void loadGlobalProxy() {
3265 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003266 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3267 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3268 String exclList = Settings.Global.getString(res,
3269 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003270 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3271 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003272 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003273 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003274 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003275 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003276 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003277 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003278 if (!proxyProperties.isValid()) {
3279 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3280 return;
3281 }
3282
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003283 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003284 mGlobalProxy = proxyProperties;
3285 }
3286 }
3287 }
3288
Jason Monk207900c2014-04-25 15:00:09 -04003289 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003290 // this information is already available as a world read/writable jvm property
3291 // so this API change wouldn't have a benifit. It also breaks the passing
3292 // of proxy info to all the JVMs.
3293 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003294 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003295 return mGlobalProxy;
3296 }
3297 }
3298
Jason Monk207900c2014-04-25 15:00:09 -04003299 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003300 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003301 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003302 proxy = null;
3303 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003304 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003306 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003307 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003308 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3309 return;
3310 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003311
3312 // This call could be coming from the PacManager, containing the port of the local
3313 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3314 // global (to get the correct local port), and send a broadcast.
3315 // TODO: Switch PacManager to have its own message to send back rather than
3316 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003317 if ((mGlobalProxy != null) && (proxy != null)
3318 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003319 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3320 mGlobalProxy = proxy;
3321 sendProxyBroadcast(mGlobalProxy);
3322 return;
3323 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003324 mDefaultProxy = proxy;
3325
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003326 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003327 if (!mDefaultProxyDisabled) {
3328 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003329 }
3330 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 }
3332
Paul Jensene0bef712014-12-10 15:12:18 -05003333 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3334 // This method gets called when any network changes proxy, but the broadcast only ever contains
3335 // the default proxy (even if it hasn't changed).
3336 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3337 // world where an app might be bound to a non-default network.
3338 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3339 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3340 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3341
3342 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3343 sendProxyBroadcast(getDefaultProxy());
3344 }
3345 }
3346
Robert Greenwalt434203a2010-10-11 16:00:27 -07003347 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003348 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3349 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 if (!TextUtils.isEmpty(proxy)) {
3351 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003352 if (data.length == 0) {
3353 return;
3354 }
3355
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 String proxyHost = data[0];
3357 int proxyPort = 8080;
3358 if (data.length > 1) {
3359 try {
3360 proxyPort = Integer.parseInt(data[1]);
3361 } catch (NumberFormatException e) {
3362 return;
3363 }
3364 }
Jason Monk207900c2014-04-25 15:00:09 -04003365 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003366 setGlobalProxy(p);
3367 }
3368 }
3369
Jason Monk207900c2014-04-25 15:00:09 -04003370 private void sendProxyBroadcast(ProxyInfo proxy) {
3371 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003372 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003373 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003375 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3376 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003377 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003378 final long ident = Binder.clearCallingIdentity();
3379 try {
3380 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3381 } finally {
3382 Binder.restoreCallingIdentity(ident);
3383 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003384 }
3385
3386 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003387 final private HashMap<Uri, Integer> mUriEventMap;
3388 final private Context mContext;
3389 final private Handler mHandler;
3390
3391 SettingsObserver(Context context, Handler handler) {
3392 super(null);
3393 mUriEventMap = new HashMap<Uri, Integer>();
3394 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003395 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396 }
3397
Erik Klineda4bfa82015-04-30 12:58:40 +09003398 void observe(Uri uri, int what) {
3399 mUriEventMap.put(uri, what);
3400 final ContentResolver resolver = mContext.getContentResolver();
3401 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 }
3403
3404 @Override
3405 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003406 Slog.wtf(TAG, "Should never be reached.");
3407 }
3408
3409 @Override
3410 public void onChange(boolean selfChange, Uri uri) {
3411 final Integer what = mUriEventMap.get(uri);
3412 if (what != null) {
3413 mHandler.obtainMessage(what.intValue()).sendToTarget();
3414 } else {
3415 loge("No matching event to send for URI=" + uri);
3416 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003417 }
3418 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003419
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003420 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003421 Slog.d(TAG, s);
3422 }
3423
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003424 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003425 Slog.e(TAG, s);
3426 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003427
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003428 private static void loge(String s, Throwable t) {
3429 Slog.e(TAG, s, t);
3430 }
3431
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003432 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003433 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003434 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3435 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3436 *
3437 * @param oldPackage Package name of the application which currently controls VPN, which will
3438 * be replaced. If there is no such application, this should should either be
3439 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3440 * @param newPackage Package name of the application which should gain control of VPN, or
3441 * {@code null} to disable.
3442 * @param userId User for whom to prepare the new VPN.
3443 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003444 * @hide
3445 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003446 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003447 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3448 int userId) {
3449 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003450 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003451
Hugo Benichi20035e02017-04-26 14:53:28 +09003452 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003453 Vpn vpn = mVpns.get(userId);
3454 if (vpn != null) {
3455 return vpn.prepare(oldPackage, newPackage);
3456 } else {
3457 return false;
3458 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003459 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003460 }
3461
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003462 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003463 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3464 * This method is used by system-privileged apps.
3465 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3466 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3467 *
3468 * @param packageName The package for which authorization state should change.
3469 * @param userId User for whom {@code packageName} is installed.
3470 * @param authorized {@code true} if this app should be able to start a VPN connection without
3471 * explicit user approval, {@code false} if not.
3472 *
Jeff Davidson05542602014-08-11 14:07:27 -07003473 * @hide
3474 */
3475 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003476 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3477 enforceCrossUserPermission(userId);
3478
Hugo Benichi20035e02017-04-26 14:53:28 +09003479 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003480 Vpn vpn = mVpns.get(userId);
3481 if (vpn != null) {
3482 vpn.setPackageAuthorization(packageName, authorized);
3483 }
Jeff Davidson05542602014-08-11 14:07:27 -07003484 }
3485 }
3486
3487 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003488 * Configure a TUN interface and return its file descriptor. Parameters
3489 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003490 * and not available in ConnectivityManager. Permissions are checked in
3491 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003492 * @hide
3493 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003494 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003495 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003496 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003497 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003498 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003499 return mVpns.get(user).establish(config);
3500 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003501 }
3502
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003503 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003504 * Start legacy VPN, controlling native daemons as needed. Creates a
3505 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003506 */
3507 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003508 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003509 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003510 final LinkProperties egress = getActiveLinkProperties();
3511 if (egress == null) {
3512 throw new IllegalStateException("Missing active network connection");
3513 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003514 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003515 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3517 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003518 }
3519
3520 /**
3521 * Return the information of the ongoing legacy VPN. This method is used
3522 * by VpnSettings and not available in ConnectivityManager. Permissions
3523 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003524 */
3525 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003526 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3527 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003528
Hugo Benichi20035e02017-04-26 14:53:28 +09003529 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003530 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003531 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003532 }
3533
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003534 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003535 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3536 * and not available in ConnectivityManager.
3537 */
3538 @Override
3539 public VpnInfo[] getAllVpnInfo() {
3540 enforceConnectivityInternalPermission();
3541 if (mLockdownEnabled) {
3542 return new VpnInfo[0];
3543 }
3544
Hugo Benichi20035e02017-04-26 14:53:28 +09003545 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003546 List<VpnInfo> infoList = new ArrayList<>();
3547 for (int i = 0; i < mVpns.size(); i++) {
3548 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3549 if (info != null) {
3550 infoList.add(info);
3551 }
3552 }
3553 return infoList.toArray(new VpnInfo[infoList.size()]);
3554 }
3555 }
3556
3557 /**
3558 * @return VPN information for accounting, or null if we can't retrieve all required
3559 * information, e.g primary underlying iface.
3560 */
3561 @Nullable
3562 private VpnInfo createVpnInfo(Vpn vpn) {
3563 VpnInfo info = vpn.getVpnInfo();
3564 if (info == null) {
3565 return null;
3566 }
3567 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3568 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3569 // the underlyingNetworks list.
3570 if (underlyingNetworks == null) {
3571 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3572 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3573 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3574 }
3575 } else if (underlyingNetworks.length > 0) {
3576 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3577 if (linkProperties != null) {
3578 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3579 }
3580 }
3581 return info.primaryUnderlyingIface == null ? null : info;
3582 }
3583
3584 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003585 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3586 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003587 * Permissions are checked in Vpn class.
3588 * @hide
3589 */
3590 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003591 public VpnConfig getVpnConfig(int userId) {
3592 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003593 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003594 Vpn vpn = mVpns.get(userId);
3595 if (vpn != null) {
3596 return vpn.getVpnConfig();
3597 } else {
3598 return null;
3599 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003600 }
3601 }
3602
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003603 @Override
3604 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003605 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3606 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3607 return false;
3608 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003609
3610 // Tear down existing lockdown if profile was removed
3611 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3612 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003613 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3614 if (profileTag == null) {
3615 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3616 return false;
3617 }
3618 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003619 final VpnProfile profile = VpnProfile.decode(
3620 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003621 if (profile == null) {
3622 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3623 setLockdownTracker(null);
3624 return true;
3625 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003626 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003627 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003628 Vpn vpn = mVpns.get(user);
3629 if (vpn == null) {
3630 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3631 return false;
3632 }
3633 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003634 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003635 } else {
3636 setLockdownTracker(null);
3637 }
3638
3639 return true;
3640 }
3641
3642 /**
3643 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3644 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3645 */
3646 private void setLockdownTracker(LockdownVpnTracker tracker) {
3647 // Shutdown any existing tracker
3648 final LockdownVpnTracker existing = mLockdownTracker;
3649 mLockdownTracker = null;
3650 if (existing != null) {
3651 existing.shutdown();
3652 }
3653
Robin Leec3736bc2017-03-10 16:19:54 +00003654 if (tracker != null) {
3655 mLockdownTracker = tracker;
3656 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003657 }
3658 }
3659
3660 private void throwIfLockdownEnabled() {
3661 if (mLockdownEnabled) {
3662 throw new IllegalStateException("Unavailable in lockdown mode");
3663 }
3664 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003665
Robin Lee244ce8e2016-01-05 18:03:46 +00003666 /**
Robin Lee17e61832016-05-09 13:46:28 +01003667 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3668 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003669 *
Robin Lee17e61832016-05-09 13:46:28 +01003670 * @return {@code true} if the service was started, the service was already connected, or there
3671 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003672 */
Robin Lee17e61832016-05-09 13:46:28 +01003673 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003674 synchronized (mVpns) {
3675 Vpn vpn = mVpns.get(userId);
3676 if (vpn == null) {
3677 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3678 // exists already.
3679 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3680 return false;
3681 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003682
Robin Lee812800c2016-05-13 15:38:08 +01003683 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003684 }
3685 }
3686
3687 @Override
Charles He36738632017-05-15 17:07:18 +01003688 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3689 enforceSettingsPermission();
3690 enforceCrossUserPermission(userId);
3691
3692 synchronized (mVpns) {
3693 Vpn vpn = mVpns.get(userId);
3694 if (vpn == null) {
3695 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3696 return false;
3697 }
3698 return vpn.isAlwaysOnPackageSupported(packageName);
3699 }
3700 }
3701
3702 @Override
Robin Leedc679712016-05-03 13:23:03 +01003703 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003704 enforceConnectivityInternalPermission();
3705 enforceCrossUserPermission(userId);
3706
3707 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3708 if (LockdownVpnTracker.isEnabled()) {
3709 return false;
3710 }
3711
Robin Lee244ce8e2016-01-05 18:03:46 +00003712 synchronized (mVpns) {
3713 Vpn vpn = mVpns.get(userId);
3714 if (vpn == null) {
3715 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3716 return false;
3717 }
Robin Lee17e61832016-05-09 13:46:28 +01003718 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003719 return false;
3720 }
Robin Lee17e61832016-05-09 13:46:28 +01003721 if (!startAlwaysOnVpn(userId)) {
3722 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003723 return false;
3724 }
3725 }
3726 return true;
3727 }
3728
3729 @Override
3730 public String getAlwaysOnVpnPackage(int userId) {
3731 enforceConnectivityInternalPermission();
3732 enforceCrossUserPermission(userId);
3733
3734 synchronized (mVpns) {
3735 Vpn vpn = mVpns.get(userId);
3736 if (vpn == null) {
3737 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3738 return null;
3739 }
3740 return vpn.getAlwaysOnPackage();
3741 }
3742 }
3743
Wink Savilleab9321d2013-06-29 21:10:57 -07003744 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003745 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003746 // TODO: Remove? Any reason to trigger a provisioning check?
3747 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003748 }
3749
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003750 /** Location to an updatable file listing carrier provisioning urls.
3751 * An example:
3752 *
3753 * <?xml version="1.0" encoding="utf-8"?>
3754 * <provisioningUrls>
3755 * <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 -07003756 * </provisioningUrls>
3757 */
3758 private static final String PROVISIONING_URL_PATH =
3759 "/data/misc/radio/provisioning_urls.xml";
3760 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003761
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003762 /** XML tag for root element. */
3763 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3764 /** XML tag for individual url */
3765 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003766 /** XML attribute for mcc */
3767 private static final String ATTR_MCC = "mcc";
3768 /** XML attribute for mnc */
3769 private static final String ATTR_MNC = "mnc";
3770
Paul Jensen434dde82015-06-11 09:43:30 -04003771 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003772 FileReader fileReader = null;
3773 XmlPullParser parser = null;
3774 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003775
3776 try {
3777 fileReader = new FileReader(mProvisioningUrlFile);
3778 parser = Xml.newPullParser();
3779 parser.setInput(fileReader);
3780 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3781
3782 while (true) {
3783 XmlUtils.nextElement(parser);
3784
3785 String element = parser.getName();
3786 if (element == null) break;
3787
Paul Jensen434dde82015-06-11 09:43:30 -04003788 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003789 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3790 try {
3791 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3792 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3793 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3794 parser.next();
3795 if (parser.getEventType() == XmlPullParser.TEXT) {
3796 return parser.getText();
3797 }
3798 }
3799 }
3800 } catch (NumberFormatException e) {
3801 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3802 }
3803 }
3804 }
3805 return null;
3806 } catch (FileNotFoundException e) {
3807 loge("Carrier Provisioning Urls file not found");
3808 } catch (XmlPullParserException e) {
3809 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3810 } catch (IOException e) {
3811 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3812 } finally {
3813 if (fileReader != null) {
3814 try {
3815 fileReader.close();
3816 } catch (IOException e) {}
3817 }
3818 }
3819 return null;
3820 }
3821
Wink Saville42d4f082013-07-20 20:31:59 -07003822 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003823 public String getMobileProvisioningUrl() {
3824 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003825 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003826 if (TextUtils.isEmpty(url)) {
3827 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003828 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003829 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003830 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003831 }
Wink Saville8cf35602013-07-10 23:00:07 -07003832 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003833 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003834 String phoneNumber = mTelephonyManager.getLine1Number();
3835 if (TextUtils.isEmpty(phoneNumber)) {
3836 phoneNumber = "0000000000";
3837 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003838 url = String.format(url,
3839 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3840 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003841 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003842 }
3843
Wink Savilleab9321d2013-06-29 21:10:57 -07003844 return url;
3845 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003846
Wink Saville948282b2013-08-29 08:55:16 -07003847 @Override
3848 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003849 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003850 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003851 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3852 return;
3853 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003854 final long ident = Binder.clearCallingIdentity();
3855 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003856 // Concatenate the range of types onto the range of NetIDs.
3857 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3858 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003859 } finally {
3860 Binder.restoreCallingIdentity(ident);
3861 }
Wink Saville948282b2013-08-29 08:55:16 -07003862 }
Wink Saville7788c612013-08-29 14:57:08 -07003863
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003864 @Override
3865 public void setAirplaneMode(boolean enable) {
3866 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003867 final long ident = Binder.clearCallingIdentity();
3868 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003869 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003870 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003871 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3872 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003873 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003874 } finally {
3875 Binder.restoreCallingIdentity(ident);
3876 }
3877 }
3878
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003879 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003880 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003881 Vpn userVpn = mVpns.get(userId);
3882 if (userVpn != null) {
3883 loge("Starting user already has a VPN");
3884 return;
3885 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003886 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003888 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003889 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3890 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003891 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003892 }
3893
3894 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003895 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003896 Vpn userVpn = mVpns.get(userId);
3897 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003898 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003899 return;
3900 }
Robin Lee17e61832016-05-09 13:46:28 +01003901 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003902 mVpns.delete(userId);
3903 }
3904 }
3905
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003906 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003907 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003908 final int vpnsSize = mVpns.size();
3909 for (int i = 0; i < vpnsSize; i++) {
3910 Vpn vpn = mVpns.valueAt(i);
3911 vpn.onUserAdded(userId);
3912 }
3913 }
3914 }
3915
3916 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003917 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003918 final int vpnsSize = mVpns.size();
3919 for (int i = 0; i < vpnsSize; i++) {
3920 Vpn vpn = mVpns.valueAt(i);
3921 vpn.onUserRemoved(userId);
3922 }
3923 }
3924 }
3925
Robin Lee89e7a692016-02-29 14:38:17 +00003926 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003927 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3928 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3929 updateLockdownVpn();
3930 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003931 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003932 }
3933 }
3934
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003935 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3936 @Override
3937 public void onReceive(Context context, Intent intent) {
3938 final String action = intent.getAction();
3939 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3940 if (userId == UserHandle.USER_NULL) return;
3941
Robin Lee323f29d2016-05-04 16:38:06 +01003942 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003943 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003944 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003945 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003946 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3947 onUserAdded(userId);
3948 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3949 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003950 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3951 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003952 }
3953 }
3954 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003955
Robin Lee95204e02017-01-27 11:59:22 +00003956 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3957 @Override
3958 public void onReceive(Context context, Intent intent) {
3959 // Try creating lockdown tracker, since user present usually means
3960 // unlocked keystore.
3961 updateLockdownVpn();
3962 mContext.unregisterReceiver(this);
3963 }
3964 };
3965
Robert Greenwalta67be032014-05-16 15:49:14 -07003966 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3967 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003968 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3969 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003970
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003971 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3972 // Map from UID to number of NetworkRequests that UID has filed.
3973 @GuardedBy("mUidToNetworkRequestCount")
3974 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3975
Robert Greenwalta67be032014-05-16 15:49:14 -07003976 private static class NetworkFactoryInfo {
3977 public final String name;
3978 public final Messenger messenger;
3979 public final AsyncChannel asyncChannel;
3980
3981 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3982 this.name = name;
3983 this.messenger = messenger;
3984 this.asyncChannel = asyncChannel;
3985 }
3986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003988 private void ensureNetworkRequestHasType(NetworkRequest request) {
3989 if (request.type == NetworkRequest.Type.NONE) {
3990 throw new IllegalArgumentException(
3991 "All NetworkRequests in ConnectivityService must have a type");
3992 }
3993 }
3994
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003995 /**
3996 * Tracks info about the requester.
3997 * Also used to notice when the calling process dies so we can self-expire
3998 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004000 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004001 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004002 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004003 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004004 final int mPid;
4005 final int mUid;
4006 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004008 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004009 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004010 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004011 mPendingIntent = pi;
4012 messenger = null;
4013 mBinder = null;
4014 mPid = getCallingPid();
4015 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004016 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004017 }
4018
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004019 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 super();
4021 messenger = m;
4022 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004023 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024 mBinder = binder;
4025 mPid = getCallingPid();
4026 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004027 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004028 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004029
4030 try {
4031 mBinder.linkToDeath(this, 0);
4032 } catch (RemoteException e) {
4033 binderDied();
4034 }
4035 }
4036
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004037 private void enforceRequestCountLimit() {
4038 synchronized (mUidToNetworkRequestCount) {
4039 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4040 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004041 throw new ServiceSpecificException(
4042 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004043 }
4044 mUidToNetworkRequestCount.put(mUid, networkRequests);
4045 }
4046 }
4047
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004049 if (mBinder != null) {
4050 mBinder.unlinkToDeath(this, 0);
4051 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004052 }
4053
4054 public void binderDied() {
4055 log("ConnectivityService NetworkRequestInfo binderDied(" +
4056 request + ", " + mBinder + ")");
4057 releaseNetworkRequest(request);
4058 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004059
4060 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004061 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004063 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064 }
4065
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004066 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4067 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4068 if (badCapability != null) {
4069 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004070 }
4071 }
4072
Erik Kline9d598e12015-07-13 16:37:51 +09004073 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004074 final SortedSet<Integer> thresholds = new TreeSet();
4075 synchronized (nai) {
4076 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4077 if (nri.request.networkCapabilities.hasSignalStrength() &&
4078 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4079 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4080 }
4081 }
4082 }
Erik Kline9d598e12015-07-13 16:37:51 +09004083 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004084 }
4085
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004086 private void updateSignalStrengthThresholds(
4087 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4088 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004089 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004090 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4091
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004092 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004093 String detail;
4094 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4095 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4096 } else {
4097 detail = reason;
4098 }
4099 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4100 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4101 }
4102
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004103 nai.asyncChannel.sendMessage(
4104 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004105 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004106 }
4107
Etan Cohen859748f2017-04-03 17:42:34 -07004108 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4109 if (nc == null) {
4110 return;
4111 }
4112 NetworkSpecifier ns = nc.getNetworkSpecifier();
4113 if (ns == null) {
4114 return;
4115 }
4116 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4117 ns.assertValidFromUid(Binder.getCallingUid());
4118 }
4119
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 @Override
4121 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004122 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004123 final NetworkRequest.Type type = (networkCapabilities == null)
4124 ? NetworkRequest.Type.TRACK_DEFAULT
4125 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004126 // If the requested networkCapabilities is null, take them instead from
4127 // the default network request. This allows callers to keep track of
4128 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004129 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004130 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4131 enforceAccessPermission();
4132 } else {
4133 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4134 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004135 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4136 // of the app when the request is filed, but we never change the request if the app
4137 // changes network state. http://b/29964605
4138 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004139 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004140 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004141
Etan Cohenba07c8c2017-02-05 10:42:27 -08004142 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 throw new IllegalArgumentException("Bad timeout specified");
4144 }
Etan Cohen859748f2017-04-03 17:42:34 -07004145 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004146
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004147 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004148 nextNetworkRequestId(), type);
4149 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004150 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151
4152 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004153 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004154 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004155 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156 }
4157 return networkRequest;
4158 }
4159
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004160 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004161 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004162 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004163 } else {
4164 enforceChangePermission();
4165 }
4166 }
4167
fenglub15e72b2015-03-20 11:29:56 -07004168 @Override
fengludb571472015-04-21 17:12:05 -07004169 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004170 enforceAccessPermission();
4171 NetworkAgentInfo nai = null;
4172 if (network == null) {
4173 return false;
4174 }
4175 synchronized (mNetworkForNetId) {
4176 nai = mNetworkForNetId.get(network.netId);
4177 }
4178 if (nai != null) {
4179 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4180 return true;
4181 }
4182 return false;
4183 }
4184
Felipe Lemeee27cab2016-06-20 16:36:29 -07004185 private boolean isSystem(int uid) {
4186 return uid < Process.FIRST_APPLICATION_UID;
4187 }
fenglub15e72b2015-03-20 11:29:56 -07004188
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004190 final int uid = Binder.getCallingUid();
4191 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004192 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004193 return;
4194 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004195 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4196 // Policy already enforced.
4197 return;
4198 }
4199 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4200 // If UID is restricted, don't allow them to bring up metered APNs.
4201 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004202 }
4203 }
4204
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 @Override
4206 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4207 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004208 checkNotNull(operation, "PendingIntent cannot be null.");
4209 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4210 enforceNetworkRequestPermissions(networkCapabilities);
4211 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004212 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004213 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004214
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004215 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004216 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4217 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004218 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004219 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4220 nri));
4221 return networkRequest;
4222 }
4223
Jeremy Joslin79294842014-12-03 17:15:28 -08004224 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4225 mHandler.sendMessageDelayed(
4226 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4227 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4228 }
4229
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004230 @Override
4231 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004232 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004233 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4234 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004235 }
4236
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004237 // In order to implement the compatibility measure for pre-M apps that call
4238 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4239 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4240 // This ensures it has permission to do so.
4241 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4242 if (nc == null) {
4243 return false;
4244 }
4245 int[] transportTypes = nc.getTransportTypes();
4246 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4247 return false;
4248 }
4249 try {
4250 mContext.enforceCallingOrSelfPermission(
4251 android.Manifest.permission.ACCESS_WIFI_STATE,
4252 "ConnectivityService");
4253 } catch (SecurityException e) {
4254 return false;
4255 }
4256 return true;
4257 }
4258
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259 @Override
4260 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4261 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004262 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4263 enforceAccessPermission();
4264 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004265
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004266 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4267 if (!ConnectivityManager.checkChangePermission(mContext)) {
4268 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4269 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4270 // onLost and onAvailable callbacks when networks move in and out of the background.
4271 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4272 // can't request networks.
4273 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4274 }
Etan Cohen859748f2017-04-03 17:42:34 -07004275 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004276
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004277 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004278 NetworkRequest.Type.LISTEN);
4279 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004280 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004281
4282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4283 return networkRequest;
4284 }
4285
4286 @Override
4287 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4288 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004289 checkNotNull(operation, "PendingIntent cannot be null.");
4290 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4291 enforceAccessPermission();
4292 }
Etan Cohen859748f2017-04-03 17:42:34 -07004293 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004294
Erik Kline7523eb32015-07-09 18:24:03 +09004295 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004296 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4297 NetworkRequest.Type.LISTEN);
4298 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004299 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004300
4301 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302 }
4303
Erik Klineacdd6392016-07-07 16:50:58 +09004304 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004305 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004306 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004307 mHandler.sendMessage(mHandler.obtainMessage(
4308 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004309 }
4310
4311 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004312 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004313 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004314 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4315 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004316 }
4317
Robert Greenwalta67be032014-05-16 15:49:14 -07004318 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004319 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004320 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4321 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4322 }
4323
4324 @Override
4325 public void unregisterNetworkFactory(Messenger messenger) {
4326 enforceConnectivityInternalPermission();
4327 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4328 }
4329
4330 private void handleUnregisterNetworkFactory(Messenger messenger) {
4331 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4332 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004333 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004334 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004335 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004336 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004337 }
4338
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 /**
4340 * NetworkAgentInfo supporting a request by requestId.
4341 * These have already been vetted (their Capabilities satisfy the request)
4342 * and the are the highest scored network available.
4343 * the are keyed off the Requests requestId.
4344 */
Hugo Benichicd952782017-09-20 11:20:14 +09004345 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4346 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004347 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4348 new SparseArray<NetworkAgentInfo>();
4349
Paul Jensen31a94f42015-02-13 14:18:39 -05004350 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4351 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4353 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004354 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4355 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4356 // there may not be a strict 1:1 correlation between the two.
4357 @GuardedBy("mNetworkForNetId")
4358 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004359
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 // NetworkAgentInfo keyed off its connecting messenger
4361 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004362 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4364 new HashMap<Messenger, NetworkAgentInfo>();
4365
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004366 @GuardedBy("mBlockedAppUids")
4367 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4368
Paul Jensen2c311d62014-11-17 12:34:51 -05004369 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004370 private final NetworkRequest mDefaultRequest;
4371
Erik Klineda4bfa82015-04-30 12:58:40 +09004372 // Request used to optionally keep mobile data active even when higher
4373 // priority networks like Wi-Fi are active.
4374 private final NetworkRequest mDefaultMobileDataRequest;
4375
Hugo Benichicd952782017-09-20 11:20:14 +09004376 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4377 synchronized (mNetworkForRequestId) {
4378 return mNetworkForRequestId.get(requestId);
4379 }
4380 }
4381
4382 private void clearNetworkForRequest(int requestId) {
4383 synchronized (mNetworkForRequestId) {
4384 mNetworkForRequestId.remove(requestId);
4385 }
4386 }
4387
4388 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4389 synchronized (mNetworkForRequestId) {
4390 mNetworkForRequestId.put(requestId, nai);
4391 }
4392 }
4393
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004394 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004395 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004396 }
4397
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004398 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004399 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004400 }
4401
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004402 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4403 return nri.request.requestId == mDefaultRequest.requestId;
4404 }
4405
Paul Jensen31a94f42015-02-13 14:18:39 -05004406 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004408 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004409 enforceConnectivityInternalPermission();
4410
Rubin Xu1bb5c082017-09-05 18:40:49 +01004411 LinkProperties lp = new LinkProperties(linkProperties);
4412 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004413 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4414 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004415 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004416 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4417 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004418 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004419 synchronized (this) {
4420 nai.networkMonitor.systemReady = mSystemReady;
4421 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004422 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4423 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004424 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004426 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004427 }
4428
4429 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4430 if (VDBG) log("Got NetworkAgent Messenger");
4431 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004432 synchronized (mNetworkForNetId) {
4433 mNetworkForNetId.put(na.network.netId, na);
4434 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4436 NetworkInfo networkInfo = na.networkInfo;
4437 na.networkInfo = null;
4438 updateNetworkInfo(na, networkInfo);
4439 }
4440
4441 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4442 LinkProperties newLp = networkAgent.linkProperties;
4443 int netId = networkAgent.network.netId;
4444
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004445 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4446 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004447 if (networkAgent.clatd != null) {
4448 networkAgent.clatd.fixupLinkProperties(oldLp);
4449 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004450
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004451 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 updateMtu(newLp, oldLp);
4453 // TODO - figure out what to do for clat
4454// for (LinkProperties lp : newLp.getStackedLinks()) {
4455// updateMtu(lp, null);
4456// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004457 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004458
Erik Kline94887872016-04-05 13:30:49 +09004459 updateRoutes(newLp, oldLp, netId);
4460 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004461
Hugo Benichi6f62b732017-06-27 15:13:20 +09004462 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004463 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004464 if (isDefaultNetwork(networkAgent)) {
4465 handleApplyDefaultProxy(newLp.getHttpProxy());
4466 } else {
4467 updateProxy(newLp, oldLp, networkAgent);
4468 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004469 // TODO - move this check to cover the whole function
4470 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004471 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004472 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4473 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004474
4475 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004476 }
4477
Joel Scherpelz668370b2017-06-08 15:35:21 +09004478 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004479 // Marks are only available on WiFi interaces. Checking for
4480 // marks on unsupported interfaces is harmless.
4481 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4482 return;
4483 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004484
Joel Scherpelz668370b2017-06-08 15:35:21 +09004485 int mark = mContext.getResources().getInteger(
4486 com.android.internal.R.integer.config_networkWakeupPacketMark);
4487 int mask = mContext.getResources().getInteger(
4488 com.android.internal.R.integer.config_networkWakeupPacketMask);
4489
4490 // Mask/mark of zero will not detect anything interesting.
4491 // Don't install rules unless both values are nonzero.
4492 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004493 return;
4494 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004495
4496 final String prefix = "iface:" + iface;
4497 try {
4498 if (add) {
4499 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4500 } else {
4501 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4502 }
4503 } catch (Exception e) {
4504 loge("Exception modifying wakeup packet monitoring: " + e);
4505 }
4506
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004507 }
4508
4509 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4510 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004511 CompareResult<String> interfaceDiff = new CompareResult<String>(
4512 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4513 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004514 for (String iface : interfaceDiff.added) {
4515 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004516 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004517 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004518 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004519 } catch (Exception e) {
4520 loge("Exception adding interface: " + e);
4521 }
4522 }
4523 for (String iface : interfaceDiff.removed) {
4524 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004525 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004526 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004527 mNetd.removeInterfaceFromNetwork(iface, netId);
4528 } catch (Exception e) {
4529 loge("Exception removing interface: " + e);
4530 }
4531 }
4532 }
4533
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004534 /**
4535 * Have netd update routes from oldLp to newLp.
4536 * @return true if routes changed between oldLp and newLp
4537 */
4538 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004539 // Compare the route diff to determine which routes should be added and removed.
4540 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4541 oldLp != null ? oldLp.getAllRoutes() : null,
4542 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543
4544 // add routes before removing old in case it helps with continuous connectivity
4545
4546 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4547 for (RouteInfo route : routeDiff.added) {
4548 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004549 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004550 try {
4551 mNetd.addRoute(netId, route);
4552 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004553 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4554 loge("Exception in addRoute for non-gateway: " + e);
4555 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
4557 }
4558 for (RouteInfo route : routeDiff.added) {
4559 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004560 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004561 try {
4562 mNetd.addRoute(netId, route);
4563 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004564 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4565 loge("Exception in addRoute for gateway: " + e);
4566 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 }
4568 }
4569
4570 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004571 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 try {
4573 mNetd.removeRoute(netId, route);
4574 } catch (Exception e) {
4575 loge("Exception in removeRoute: " + e);
4576 }
4577 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004578 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004579 }
Erik Kline41368502015-06-17 13:19:54 +09004580
Erik Kline94887872016-04-05 13:30:49 +09004581 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4582 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4583 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004584 }
Erik Kline94887872016-04-05 13:30:49 +09004585
4586 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004587 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004588 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004589 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004590 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4591 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004592 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004593 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004594 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4595 if (defaultNai != null && defaultNai.network.netId == netId) {
4596 setDefaultDnsSystemProperties(dnses);
4597 }
Erik Kline94887872016-04-05 13:30:49 +09004598 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004599 }
4600
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004601 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4602 int last = 0;
4603 for (InetAddress dns : dnses) {
4604 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004605 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004606 }
4607 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004608 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004609 }
4610 mNumDnsEntries = last;
4611 }
4612
Erik Kline4edba012017-04-07 15:29:29 +09004613 private void setNetDnsProperty(int which, String value) {
4614 final String key = "net.dns" + which;
4615 // Log and forget errors setting unsupported properties.
4616 try {
4617 mSystemProperties.set(key, value);
4618 } catch (Exception e) {
4619 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4620 }
4621 }
4622
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004623 private String getNetworkPermission(NetworkCapabilities nc) {
4624 // TODO: make these permission strings AIDL constants instead.
4625 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4626 return NetworkManagementService.PERMISSION_SYSTEM;
4627 }
4628 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4629 return NetworkManagementService.PERMISSION_NETWORK;
4630 }
4631 return null;
4632 }
4633
Paul Jensen3d194ea2015-06-16 14:27:36 -04004634 /**
4635 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4636 * augmented with any stateful capabilities implied from {@code networkAgent}
4637 * (e.g., validated status and captive portal status).
4638 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004639 * @param oldScore score of the network before any of the changes that prompted us
4640 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004641 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004642 * @param networkCapabilities the new network capabilities.
4643 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004644 private void updateCapabilities(
4645 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004646 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichi80e8e0f2017-08-18 14:41:22 +09004647 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4648 networkCapabilities)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004649 // TODO: consider not complaining when a network agent degrade its capabilities if this
4650 // does not cause any request (that is not a listen) currently matching that agent to
4651 // stop being matched by the updated agent.
Hugo Benichi683ea482017-07-25 11:40:56 +09004652 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4653 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004654 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004655 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004656 }
4657
Paul Jensen3d194ea2015-06-16 14:27:36 -04004658 // Don't modify caller's NetworkCapabilities.
4659 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004660 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004661 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4662 } else {
4663 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4664 }
Paul Jensene0988542015-06-25 15:30:08 -04004665 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004666 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4667 } else {
4668 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4669 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004670 if (nai.isBackgroundNetwork()) {
4671 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4672 } else {
4673 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4674 }
4675
4676 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4677
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004678 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4679 final String newPermission = getNetworkPermission(networkCapabilities);
4680 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004681 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004682 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004683 } catch (RemoteException e) {
4684 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004685 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004686 }
4687
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004688 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004689 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004690 prevNc = nai.networkCapabilities;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004691 nai.networkCapabilities = networkCapabilities;
4692 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004693
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004694 if (nai.getCurrentScore() == oldScore &&
4695 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4696 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4697 // the change we're processing can't affect any requests, it can only affect the listens
4698 // on this network. We might have been called by rematchNetworkAndRequests when a
4699 // network changed foreground state.
4700 processListenRequests(nai, true);
4701 } else {
4702 // If the requestable capabilities have changed or the score changed, we can't have been
4703 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004704 rematchAllNetworksAndRequests(nai, oldScore);
4705 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004706 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004707
4708 // Report changes that are interesting for network statistics tracking.
4709 if (prevNc != null) {
4710 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
4711 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED);
4712 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
4713 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING);
4714 if (meteredChanged || roamingChanged) {
4715 notifyIfacesChangedForNetworkStats();
4716 }
4717 }
4718
4719 if (!networkCapabilities.hasTransport(TRANSPORT_VPN)) {
4720 // Tell VPNs about updated capabilities, since they may need to
4721 // bubble those changes through.
4722 synchronized (mVpns) {
4723 for (int i = 0; i < mVpns.size(); i++) {
4724 final Vpn vpn = mVpns.valueAt(i);
4725 vpn.updateCapabilities();
4726 }
4727 }
4728 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004729 }
4730
Hugo Benichief502882017-09-01 01:23:32 +00004731 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4732 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4733 // Ignore updates for disconnected networks
4734 return;
4735 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004736 // newLp is already a defensive copy.
4737 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004738 if (VDBG) {
4739 log("Update of LinkProperties for " + nai.name() +
4740 "; created=" + nai.created +
4741 "; everConnected=" + nai.everConnected);
4742 }
4743 LinkProperties oldLp = nai.linkProperties;
4744 synchronized (nai) {
4745 nai.linkProperties = newLp;
4746 }
4747 if (nai.everConnected) {
4748 updateLinkProperties(nai, oldLp);
4749 }
4750 }
4751
Paul Jensenc8b9a742014-09-30 15:37:41 -04004752 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004753 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4754 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004755 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004756 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004757 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4758 }
4759 }
4760
Robert Greenwalt7b816022014-04-18 15:25:25 -07004761 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4762 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004763 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004764 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4765 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 }
4767 }
4768
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004769 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4770 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004771 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004772 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004773 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4774 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004775 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004776 sendIntent(nri.mPendingIntent, intent);
4777 }
4778 // else not handled
4779 }
4780
4781 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4782 mPendingIntentWakeLock.acquire();
4783 try {
4784 if (DBG) log("Sending " + pendingIntent);
4785 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4786 } catch (PendingIntent.CanceledException e) {
4787 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4788 mPendingIntentWakeLock.release();
4789 releasePendingNetworkRequest(pendingIntent);
4790 }
4791 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4792 }
4793
4794 @Override
4795 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4796 String resultData, Bundle resultExtras) {
4797 if (DBG) log("Finished sending " + pendingIntent);
4798 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004799 // Release with a delay so the receiving client has an opportunity to put in its
4800 // own request.
4801 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004802 }
4803
Hugo Benichidba33db2017-03-23 22:40:44 +09004804 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004805 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004806 if (nri.messenger == null) {
4807 return; // Default request has no msgr
4808 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004809 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004810 // TODO: check if defensive copies of data is needed.
4811 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004812 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004813 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4814 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004815 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004816 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004817 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004818 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004819 break;
4820 }
4821 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004822 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004823 break;
4824 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004825 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004826 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004827 break;
4828 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004829 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004830 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004831 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004832 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004833 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004834 String notification = ConnectivityManager.getCallbackName(notificationType);
4835 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004836 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004837 nri.messenger.send(msg);
4838 } catch (RemoteException e) {
4839 // may occur naturally in the race of binder death.
4840 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4841 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004842 }
4843
Hugo Benichidba33db2017-03-23 22:40:44 +09004844 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4845 bundle.putParcelable(t.getClass().getSimpleName(), t);
4846 }
4847
Paul Jensenc8b9a742014-09-30 15:37:41 -04004848 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004849 if (nai.numRequestNetworkRequests() != 0) {
4850 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4851 NetworkRequest nr = nai.requestAt(i);
4852 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004853 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004854 loge("Dead network still had at least " + nr);
4855 break;
4856 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004857 }
4858 nai.asyncChannel.disconnect();
4859 }
4860
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4862 if (oldNetwork == null) {
4863 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4864 return;
4865 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004866 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004867
4868 // If we get here it means that the last linger timeout for this network expired. So there
4869 // must be no other active linger timers, and we must stop lingering.
4870 oldNetwork.clearLingerState();
4871
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004872 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004873 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004874 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004875 } else {
4876 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004877 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4878 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004879 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 }
4881
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004882 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004883 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004884 setupDataActivityTracking(newNetwork);
4885 try {
4886 mNetd.setDefaultNetId(newNetwork.network.netId);
4887 } catch (Exception e) {
4888 loge("Exception setting default network :" + e);
4889 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004890 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004891 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004892 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004893 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004894 }
4895
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004896 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004897 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4898 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4899 NetworkRequest nr = nri.request;
4900 if (!nr.isListen()) continue;
4901 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4902 nai.removeRequest(nri.request.requestId);
4903 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4904 }
4905 }
4906
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004907 if (capabilitiesChanged) {
4908 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4909 }
4910
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004911 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4912 NetworkRequest nr = nri.request;
4913 if (!nr.isListen()) continue;
4914 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4915 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004916 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004917 }
4918 }
4919 }
4920
Paul Jensen2161a8e2014-09-11 11:00:39 -04004921 // Handles a network appearing or improving its score.
4922 //
4923 // - Evaluates all current NetworkRequests that can be
4924 // satisfied by newNetwork, and reassigns to newNetwork
4925 // any such requests for which newNetwork is the best.
4926 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004927 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004928 // needed. A network is needed if it is the best network for
4929 // one or more NetworkRequests, or if it is a VPN.
4930 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004931 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004932 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004933 //
4934 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4935 // networks that have no chance (i.e. even if validated)
4936 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004937 //
4938 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4939 // it does not remove NetworkRequests that other Networks could better satisfy.
4940 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4941 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4942 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004943 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004944 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004945 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4946 // performed to tear down unvalidated networks that have no chance (i.e. even if
4947 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004948 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004949 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004950 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004951 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004952 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004953 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004954
4955 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4956 final int score = newNetwork.getCurrentScore();
4957
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004958 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004959
Paul Jensen2161a8e2014-09-11 11:00:39 -04004960 // Find and migrate to this Network any NetworkRequests for
4961 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004962 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004963 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004964 NetworkCapabilities nc = newNetwork.networkCapabilities;
4965 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004966 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004967 // Process requests in the first pass and listens in the second pass. This allows us to
4968 // change a network's capabilities depending on which requests it has. This is only
4969 // correct if the change in capabilities doesn't affect whether the network satisfies
4970 // requests or not, and doesn't affect the network's score.
4971 if (nri.request.isListen()) continue;
4972
Hugo Benichicd952782017-09-20 11:20:14 +09004973 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004974 final boolean satisfies = newNetwork.satisfies(nri.request);
4975 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004976 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004977 log("Network " + newNetwork.name() + " was already satisfying" +
4978 " request " + nri.request.requestId + ". No change.");
4979 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004980 keep = true;
4981 continue;
4982 }
4983
4984 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004985 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004986 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004987 // next check if it's better than any current network we're using for
4988 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004989 if (VDBG) {
4990 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004991 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004992 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004994 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004995 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004996 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004997 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004998 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004999 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005000 affectedNetworks.add(currentNetwork);
5001 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005002 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005003 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005004 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005005 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005006 if (!newNetwork.addRequest(nri.request)) {
5007 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5008 }
5009 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005010 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005011 // Tell NetworkFactories about the new score, so they can stop
5012 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005013 // TODO - this could get expensive if we have alot of requests for this
5014 // network. Think about if there is a way to reduce this. Push
5015 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005016 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005017 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005018 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005019 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005020 if (currentNetwork != null) {
5021 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5022 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005023 }
5024 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005025 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005026 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5027 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005028 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005029 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5030 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5031 // This means this code doesn't have to handle the case where "currentNetwork" no
5032 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5033 if (DBG) {
5034 log("Network " + newNetwork.name() + " stopped satisfying" +
5035 " request " + nri.request.requestId);
5036 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005037 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005038 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005039 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005040 sendUpdatedScoreToFactories(nri.request, 0);
5041 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005042 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5043 newNetwork.name() +
5044 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005045 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005046 // TODO: Technically, sending CALLBACK_LOST here is
5047 // incorrect if there is a replacement network currently
5048 // connected that can satisfy nri, which is a request
5049 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005050 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5051 // so this code is only incorrect for a network that loses
5052 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005053 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005054 }
5055 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005056 if (isNewDefault) {
5057 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005058 makeDefault(newNetwork);
5059 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005060 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005061 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005062 // Have a new default network, release the transition wakelock in
5063 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005064 }
5065
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005066 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5067 Slog.wtf(TAG, String.format(
5068 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005069 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005070 }
5071 if (newNetwork.getCurrentScore() != score) {
5072 Slog.wtf(TAG, String.format(
5073 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005074 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005075 }
5076
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005077 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005078 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5079 // If the network went from background to foreground or vice versa, we need to update
5080 // its foreground state. It is safe to do this after rematching the requests because
5081 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5082 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005083 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005084 } else {
5085 processListenRequests(newNetwork, false);
5086 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005087
Paul Jensencf4c2c62015-07-01 14:16:32 -04005088 // do this after the default net is switched, but
5089 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005090 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005091
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005092 // Linger any networks that are no longer needed. This should be done after sending the
5093 // available callback for newNetwork.
5094 for (NetworkAgentInfo nai : affectedNetworks) {
5095 updateLingerState(nai, now);
5096 }
5097 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5098 // does not need to be done in any particular order.
5099 updateLingerState(newNetwork, now);
5100
Paul Jensencf4c2c62015-07-01 14:16:32 -04005101 if (isNewDefault) {
5102 // Maintain the illusion: since the legacy API only
5103 // understands one network at a time, we must pretend
5104 // that the current default network disconnected before
5105 // the new one connected.
5106 if (oldDefaultNetwork != null) {
5107 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5108 oldDefaultNetwork, true);
5109 }
5110 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5111 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5112 notifyLockdownVpn(newNetwork);
5113 }
5114
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005116 // Notify battery stats service about this network, both the normal
5117 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005118 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005119 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005120 final IBatteryStats bs = BatteryStatsService.getService();
5121 final int type = newNetwork.networkInfo.getType();
5122
5123 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5124 bs.noteNetworkInterfaceType(baseIface, type);
5125 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5126 final String stackedIface = stacked.getInterfaceName();
5127 bs.noteNetworkInterfaceType(stackedIface, type);
5128 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5129 }
5130 } catch (RemoteException ignored) {
5131 }
5132
Robert Greenwalt152ed372014-12-17 17:19:53 -08005133 // This has to happen after the notifyNetworkCallbacks as that tickles each
5134 // ConnectivityManager instance so that legacy requests correctly bind dns
5135 // requests to this network. The legacy users are listening for this bcast
5136 // and will generally do a dns request so they can ensureRouteToHost and if
5137 // they do that before the callbacks happen they'll use the default network.
5138 //
5139 // TODO: Is there still a race here? We send the broadcast
5140 // after sending the callback, but if the app can receive the
5141 // broadcast before the callback, it might still break.
5142 //
5143 // This *does* introduce a race where if the user uses the new api
5144 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5145 // they may get old info. Reverse this after the old startUsing api is removed.
5146 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005147 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5148 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005149 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005150 // legacy type tracker filters out repeat adds
5151 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5152 }
5153 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005154
5155 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5156 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5157 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5158 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5159 if (newNetwork.isVPN()) {
5160 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5161 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005162 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005163 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5164 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005165 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005166 if (nai.getLingerExpiry() > 0) {
5167 // This network has active linger timers and no requests, but is not
5168 // lingering. Linger it.
5169 //
5170 // One way (the only way?) this can happen if this network is unvalidated
5171 // and became unneeded due to another network improving its score to the
5172 // point where this network will no longer be able to satisfy any requests
5173 // even if it validates.
5174 updateLingerState(nai, now);
5175 } else {
5176 if (DBG) log("Reaping " + nai.name());
5177 teardownUnneededNetwork(nai);
5178 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005179 }
5180 }
5181 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005182 }
5183
Paul Jensen1c7ba022015-06-16 14:27:36 -04005184 /**
5185 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5186 * being disconnected.
5187 * @param changed If only one Network's score or capabilities have been modified since the last
5188 * time this function was called, pass this Network in this argument, otherwise pass
5189 * null.
5190 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5191 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5192 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5193 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5194 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005195 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005196 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005197 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5198 // to avoid the slowness. It is not simply enough to process just "changed", for
5199 // example in the case where "changed"'s score decreases and another network should begin
5200 // satifying a NetworkRequest that "changed" currently satisfies.
5201
5202 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5203 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5204 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005205 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005206 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005207 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005208 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005209 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5210 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5211 // Rematch higher scoring networks first to prevent requests first matching a lower
5212 // scoring network and then a higher scoring network, which could produce multiple
5213 // callbacks and inadvertently unlinger networks.
5214 Arrays.sort(nais);
5215 for (NetworkAgentInfo nai : nais) {
5216 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005217 // Only reap the last time through the loop. Reaping before all rematching
5218 // is complete could incorrectly teardown a network that hasn't yet been
5219 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005220 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005221 : ReapUnvalidatedNetworks.REAP,
5222 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005223 }
5224 }
5225 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005226
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005227 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005228 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005229 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005230 // For now only update icons for default connection.
5231 // TODO: Update WiFi and cellular icons separately. b/17237507
5232 if (!isDefaultNetwork(nai)) return;
5233
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005234 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005235 // Don't repeat publish.
5236 if (newInetCondition == mDefaultInetConditionPublished) return;
5237
5238 mDefaultInetConditionPublished = newInetCondition;
5239 sendInetConditionBroadcast(nai.networkInfo);
5240 }
5241
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005242 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5243 if (mLockdownTracker != null) {
5244 if (nai != null && nai.isVPN()) {
5245 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5246 } else {
5247 mLockdownTracker.onNetworkInfoChanged();
5248 }
5249 }
5250 }
5251
Robert Greenwalt7b816022014-04-18 15:25:25 -07005252 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005253 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005254 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005255 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005256 synchronized (networkAgent) {
5257 oldInfo = networkAgent.networkInfo;
5258 networkAgent.networkInfo = newInfo;
5259 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005260 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 if (DBG) {
5263 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5264 (oldInfo == null ? "null" : oldInfo.getState()) +
5265 " to " + state);
5266 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005267
Robin Lee585e2482016-05-01 23:00:00 +01005268 if (!networkAgent.created
5269 && (state == NetworkInfo.State.CONNECTED
5270 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005271
5272 // A network that has just connected has zero requests and is thus a foreground network.
5273 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5274
Robert Greenwalt7b816022014-04-18 15:25:25 -07005275 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005276 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005277 if (networkAgent.isVPN()) {
5278 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005279 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5280 (networkAgent.networkMisc == null ||
5281 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005282 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005283 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005284 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005285 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005286 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005287 loge("Error creating network " + networkAgent.network.netId + ": "
5288 + e.getMessage());
5289 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005290 }
Paul Jenseneec75412014-08-04 12:21:19 -04005291 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005292 }
5293
5294 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5295 networkAgent.everConnected = true;
5296
Robert Greenwalt7b816022014-04-18 15:25:25 -07005297 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005298 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005299
Paul Jensenca8f16a2014-05-09 12:47:55 -04005300 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005301 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005302
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005303 if (networkAgent.isVPN()) {
5304 // Temporarily disable the default proxy (not global).
5305 synchronized (mProxyLock) {
5306 if (!mDefaultProxyDisabled) {
5307 mDefaultProxyDisabled = true;
5308 if (mGlobalProxy == null && mDefaultProxy != null) {
5309 sendProxyBroadcast(null);
5310 }
5311 }
5312 }
5313 // TODO: support proxy per network.
5314 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005315
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005316 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5317 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5318 // capabilities, so it only needs to be done once on initial connect, not every time the
5319 // network's capabilities change. Note that we do this before rematching the network,
5320 // so we could decide to tear it down immediately afterwards. That's fine though - on
5321 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5322 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005323 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005324
Paul Jensen2161a8e2014-09-11 11:00:39 -04005325 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005326 final long now = SystemClock.elapsedRealtime();
5327 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005328
5329 // This has to happen after matching the requests, because callbacks are just requests.
5330 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005331 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005332 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005333 if (networkAgent.isVPN()) {
5334 synchronized (mProxyLock) {
5335 if (mDefaultProxyDisabled) {
5336 mDefaultProxyDisabled = false;
5337 if (mGlobalProxy == null && mDefaultProxy != null) {
5338 sendProxyBroadcast(mDefaultProxy);
5339 }
5340 }
5341 }
5342 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005343 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5344 state == NetworkInfo.State.SUSPENDED) {
5345 // going into or coming out of SUSPEND: rescore and notify
5346 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005347 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005348 }
5349 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5350 ConnectivityManager.CALLBACK_SUSPENDED :
5351 ConnectivityManager.CALLBACK_RESUMED));
5352 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005353 }
5354 }
5355
Robert Greenwaltac96c522014-06-03 16:43:57 -07005356 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005357 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005358 if (score < 0) {
5359 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5360 "). Bumping score to min of 0");
5361 score = 0;
5362 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005363
Paul Jensen2161a8e2014-09-11 11:00:39 -04005364 final int oldScore = nai.getCurrentScore();
5365 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005366
Paul Jensen85cf78e2015-06-25 13:25:07 -04005367 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005368
Paul Jensenc8b9a742014-09-30 15:37:41 -04005369 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005370 }
5371
Erik Klinec75d4fa2017-02-15 19:59:17 +09005372 // Notify only this one new request of the current state. Transfer all the
5373 // current state by calling NetworkCapabilities and LinkProperties callbacks
5374 // so that callers can be guaranteed to have as close to atomicity in state
5375 // transfer as can be supported by this current API.
5376 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005377 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005378 if (nri.mPendingIntent != null) {
5379 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5380 // Attempt no subsequent state pushes where intents are involved.
5381 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005382 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005383
5384 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5385 // Whether a network is currently suspended is also an important
5386 // element of state to be transferred (it would not otherwise be
5387 // delivered by any currently available mechanism).
5388 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5389 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5390 }
5391 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5392 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005393 }
5394
Robert Greenwalt8d482522015-06-24 13:23:42 -07005395 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005396 // The NetworkInfo we actually send out has no bearing on the real
5397 // state of affairs. For example, if the default connection is mobile,
5398 // and a request for HIPRI has just gone away, we need to pretend that
5399 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5400 // the state to DISCONNECTED, even though the network is of type MOBILE
5401 // and is still connected.
5402 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5403 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005404 if (state != DetailedState.DISCONNECTED) {
5405 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005406 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005407 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005408 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005409 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5410 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5411 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5412 if (info.isFailover()) {
5413 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5414 nai.networkInfo.setFailover(false);
5415 }
5416 if (info.getReason() != null) {
5417 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5418 }
5419 if (info.getExtraInfo() != null) {
5420 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5421 }
5422 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005423 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005424 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005425 if (newDefaultAgent != null) {
5426 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5427 newDefaultAgent.networkInfo);
5428 } else {
5429 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5430 }
5431 }
5432 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5433 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005434 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005435 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005436 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005437 }
5438 }
5439 }
5440
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005441 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005442 if (VDBG) {
5443 String notification = ConnectivityManager.getCallbackName(notifyType);
5444 log("notifyType " + notification + " for " + networkAgent.name());
5445 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005446 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5447 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005448 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5449 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005450 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5451 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005452 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005453 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005454 } else {
5455 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5456 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005457 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005458 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005459
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005460 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5461 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5462 }
5463
Jeff Sharkey69736342014-12-08 14:50:12 -08005464 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005465 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5466 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005467 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005468 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005469 try {
5470 mStatsService.forceUpdateIfaces();
5471 } catch (Exception ignored) {
5472 }
5473 }
5474
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005475 @Override
5476 public boolean addVpnAddress(String address, int prefixLength) {
5477 throwIfLockdownEnabled();
5478 int user = UserHandle.getUserId(Binder.getCallingUid());
5479 synchronized (mVpns) {
5480 return mVpns.get(user).addAddress(address, prefixLength);
5481 }
5482 }
5483
5484 @Override
5485 public boolean removeVpnAddress(String address, int prefixLength) {
5486 throwIfLockdownEnabled();
5487 int user = UserHandle.getUserId(Binder.getCallingUid());
5488 synchronized (mVpns) {
5489 return mVpns.get(user).removeAddress(address, prefixLength);
5490 }
5491 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005492
5493 @Override
5494 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5495 throwIfLockdownEnabled();
5496 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005497 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005498 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005499 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005500 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005501 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005502 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005503 }
5504 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005505 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005506
5507 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005508 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005509 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005510 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005511 }
5512
5513 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005514 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5515 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5516 enforceKeepalivePermission();
5517 mKeepaliveTracker.startNattKeepalive(
5518 getNetworkAgentInfoForNetwork(network),
5519 intervalSeconds, messenger, binder,
5520 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5521 }
5522
5523 @Override
5524 public void stopKeepalive(Network network, int slot) {
5525 mHandler.sendMessage(mHandler.obtainMessage(
5526 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5527 }
5528
5529 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005530 public void factoryReset() {
5531 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005532
5533 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5534 return;
5535 }
5536
Robin Lee3b3dd942015-05-12 18:14:58 +01005537 final int userId = UserHandle.getCallingUserId();
5538
Stuart Scottf1fb3972015-04-02 18:00:02 -07005539 // Turn airplane mode off
5540 setAirplaneMode(false);
5541
Stuart Scotte3e314d2015-04-20 14:07:45 -07005542 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5543 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005544 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005545 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005546 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005547 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005548 }
5549
Stuart Scotte3e314d2015-04-20 14:07:45 -07005550 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005551 // Remove always-on package
5552 synchronized (mVpns) {
5553 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5554 if (alwaysOnPackage != null) {
5555 setAlwaysOnVpnPackage(userId, null, false);
5556 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5557 }
5558 }
5559
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005560 // Turn Always-on VPN off
5561 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5562 final long ident = Binder.clearCallingIdentity();
5563 try {
5564 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5565 mLockdownEnabled = false;
5566 setLockdownTracker(null);
5567 } finally {
5568 Binder.restoreCallingIdentity(ident);
5569 }
5570 }
5571
Stuart Scotte3e314d2015-04-20 14:07:45 -07005572 // Turn VPN off
5573 VpnConfig vpnConfig = getVpnConfig(userId);
5574 if (vpnConfig != null) {
5575 if (vpnConfig.legacy) {
5576 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5577 } else {
5578 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5579 // in the future without user intervention.
5580 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005581
Victor Changb04a5ea2016-05-30 20:36:30 +01005582 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005583 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005584 }
5585 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005586
5587 Settings.Global.putString(mContext.getContentResolver(),
5588 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005589 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005590
5591 @VisibleForTesting
5592 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5593 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5594 return new NetworkMonitor(context, handler, nai, defaultRequest);
5595 }
Erik Kline48f12f22016-04-14 17:30:59 +09005596
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005597 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005598 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5599 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005600 }
5601
5602 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005603 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5604 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5605 }
5606
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005607 @VisibleForTesting
5608 public boolean hasService(String name) {
5609 return ServiceManager.checkService(name) != null;
5610 }
5611
Hugo Benichi64901e52017-10-19 14:42:40 +09005612 @VisibleForTesting
5613 protected IpConnectivityMetrics.Logger metricsLogger() {
5614 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5615 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005616 }
5617
5618 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005619 int[] transports = nai.networkCapabilities.getTransportTypes();
5620 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005621 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005622
5623 private static boolean toBool(int encodedBoolean) {
5624 return encodedBoolean != 0; // Only 0 means false.
5625 }
5626
5627 private static int encodeBool(boolean b) {
5628 return b ? 1 : 0;
5629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630}