blob: 0d2e941858241874960f8c8ca6927248e172a638 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090022import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040027import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060032import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060034import static android.net.NetworkCapabilities.TRANSPORT_VPN;
35
Hugo Benichia0385682017-03-22 17:07:57 +090036import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037
Wenchao Tongf5ea3402015-03-04 13:26:38 -080038import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080039import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090040import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070041import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090058import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff 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 Hea0a87e82017-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;
Hugo Benichib577d652017-06-27 15:13:20 +0900146import 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;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600150
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700151import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700152
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700153import org.xmlpull.v1.XmlPullParser;
154import org.xmlpull.v1.XmlPullParserException;
155
156import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700158import java.io.FileNotFoundException;
159import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700160import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700162import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700163import java.net.InetAddress;
164import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700165import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700166import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700168import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700170import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700172import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700173import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600174import java.util.SortedSet;
175import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177/**
178 * @hide
179 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800180public class ConnectivityService extends IConnectivityManager.Stub
181 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900182 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Erik Kline7747fd42017-05-12 16:52:48 +0900184 public static final String DIAG_ARG = "--diag";
185 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900186 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900187
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900188 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700189 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
Jake Hamby786e71a2014-02-06 14:43:50 -0800191 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900192 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700193
Jeff Sharkey899223b2012-08-04 15:24:58 -0700194 // TODO: create better separation between radio types and network types
195
Robert Greenwalt42acef32009-08-12 16:08:25 -0700196 // how long to wait before switching back to a radio's default network
197 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
198 // system property that can override the above value
199 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
200 "android.telephony.apn-restore";
201
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900202 // How long to wait before putting up a "This network doesn't have an Internet connection,
203 // connect anyway?" dialog after the user selects a network that doesn't validate.
204 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
205
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900206 // Default to 30s linger time-out. Modifiable only for testing.
207 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
208 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
209 @VisibleForTesting
210 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
211
Jeremy Joslin79294842014-12-03 17:15:28 -0800212 // How long to delay to removal of a pending intent based request.
213 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
214 private final int mReleasePendingIntentDelayMs;
215
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900216 private MockableSystemProperties mSystemProperties;
217
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800218 private Tethering mTethering;
219
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700220 private final PermissionMonitor mPermissionMonitor;
221
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700222 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700223
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700224 @GuardedBy("mVpns")
225 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700226
Hugo Benichi69744342017-11-27 10:57:16 +0900227 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
228 // a direct call to LockdownVpnTracker.isEnabled().
229 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700230 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900231 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700232 private LockdownVpnTracker mLockdownTracker;
233
Erik Klineda4bfa82015-04-30 12:58:40 +0900234 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700237 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800239 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700242 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700244 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800245 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700246 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900247 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700249 private String mCurrentTcpBufferSizes;
250
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251 private static final int ENABLED = 1;
252 private static final int DISABLED = 0;
253
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
256 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400259 // Tear down networks that have no chance (e.g. even if validated) of becoming
260 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 // all networks have been rematched against all NetworkRequests.
262 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Don't reap networks. This should be passed when some networks have not yet been
264 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 DONT_REAP
266 };
267
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900268 private enum UnneededFor {
269 LINGER, // Determine whether this network is unneeded and should be lingered.
270 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
271 }
272
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 * used internally to change our mobile data enabled flag
275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277
278 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700280 * from one net to another. Clear happens when we get a new
281 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
282 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286 /**
287 * used internally to reload global proxy settings
288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700291 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400292 * PAC manager has received new port.
293 */
294 private static final int EVENT_PROXY_HAS_CHANGED = 16;
295
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 /**
297 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700298 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 */
300 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
301
Robert Greenwalt7b816022014-04-18 15:25:25 -0700302 /**
303 * used internally when registering NetworkAgents
304 * obj = Messenger
305 */
306 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
307
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 /**
309 * used to add a network request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
313
314 /**
315 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900316 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 * cancel it.
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
321
322 /**
323 * used to add a network listener - no request
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
327
328 /**
329 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400330 * arg1 = UID of caller
331 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
334
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 /**
336 * used internally when registering NetworkFactories
337 * obj = Messenger
338 */
339 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
340
Robert Greenwalt27711812014-06-25 16:45:57 -0700341 /**
342 * used internally to expire a wakelock when transitioning
343 * from one net to another. Expire happens when we fail to find
344 * a new network (typically after 1 minute) -
345 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
346 * a replacement network.
347 */
348 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
349
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700350 /**
351 * Used internally to indicate the system is ready.
352 */
353 private static final int EVENT_SYSTEM_READY = 25;
354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 /**
356 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400357 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 */
359 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
360
361 /**
362 * used to remove a pending intent and its associated network request.
363 * arg1 = UID of caller
364 * obj = PendingIntent
365 */
366 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
367
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 /**
369 * used to specify whether a network should be used even if unvalidated.
370 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
371 * arg2 = whether to remember this choice in the future (1 or 0)
372 * obj = network
373 */
374 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
375
376 /**
377 * used to ask the user to confirm a connection to an unvalidated network.
378 * obj = network
379 */
380 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700381
Erik Klineda4bfa82015-04-30 12:58:40 +0900382 /**
383 * used internally to (re)configure mobile data always-on settings.
384 */
385 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
386
Paul Jensen694f2b82015-06-17 14:15:39 -0400387 /**
388 * used to add a network listener with a pending intent
389 * obj = NetworkRequestInfo
390 */
391 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
392
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900393 /**
394 * used to specify whether a network should not be penalized when it becomes unvalidated.
395 */
396 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
397
398 /**
399 * used to trigger revalidation of a network.
400 */
401 private static final int EVENT_REVALIDATE_NETWORK = 36;
402
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900403 private static String eventName(int what) {
404 return sMagicDecoderRing.get(what, Integer.toString(what));
405 }
406
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900407 /** Handler thread used for both of the handlers below. */
408 @VisibleForTesting
409 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700410 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700411 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700412 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700413 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700414
Mike Lockwood0f79b542009-08-14 14:18:49 -0400415 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800416 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400417
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700418 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700419 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800420 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700421
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400423 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700424 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700425 private boolean mDefaultProxyDisabled = false;
426
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400428 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429
Jason Monk602b2322013-07-03 17:04:33 -0400430 private PacManager mPacManager = null;
431
Erik Klineda4bfa82015-04-30 12:58:40 +0900432 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400434 private UserManager mUserManager;
435
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700436 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700438
Robert Greenwalt50393202011-06-21 17:26:14 -0700439 // the set of network types that can only be enabled by system/sig apps
440 List mProtectedNetworks;
441
John Spurlockbf991a82013-06-24 14:20:23 -0400442 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700443
Wink Savilleab9321d2013-06-29 21:10:57 -0700444 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400445
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900446 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900447 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900448 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900449
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700450 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
451 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700452 private final static int MAX_NET_ID = 65535;
453 private int mNextNetId = MIN_NET_ID;
454
Robert Greenwalt34524f02014-05-18 16:22:10 -0700455 // sequence number of NetworkRequests
456 private int mNextNetworkRequestId = 1;
457
Erik Kline7523eb32015-07-09 18:24:03 +0900458 // NetworkRequest activity String log entries.
459 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
460 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
461
Hugo Benichic2ae2872016-07-11 11:05:12 +0900462 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900463 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900464 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
465
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900466 private static final int MAX_WAKELOCK_LOGS = 20;
467 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900468 private int mTotalWakelockAcquisitions = 0;
469 private int mTotalWakelockReleases = 0;
470 private long mTotalWakelockDurationMs = 0;
471 private long mMaxWakelockDurationMs = 0;
472 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900473
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700474 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
475 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400476 private static class ValidationLog {
477 final Network mNetwork;
478 final String mNetworkExtraInfo;
479 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
482 mNetwork = network;
483 mNetworkExtraInfo = networkExtraInfo;
484 mLog = log;
485 }
486 }
487 private final ArrayDeque<ValidationLog> mValidationLogs =
488 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
489
490 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900491 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700492 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
493 mValidationLogs.removeLast();
494 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400495 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 }
497 }
498
Hugo Benichif9fdf872016-07-28 17:53:06 +0900499 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900500
Erik Kline065ab6e2016-10-02 18:02:14 +0900501 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900502 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900503
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700504 /**
505 * Implements support for the legacy "one network per network type" model.
506 *
507 * We used to have a static array of NetworkStateTrackers, one for each
508 * network type, but that doesn't work any more now that we can have,
509 * for example, more that one wifi network. This class stores all the
510 * NetworkAgentInfo objects that support a given type, but the legacy
511 * API will only see the first one.
512 *
513 * It serves two main purposes:
514 *
515 * 1. Provide information about "the network for a given type" (since this
516 * API only supports one).
517 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
518 * the first network for a given type changes, or if the default network
519 * changes.
520 */
521 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900523 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 /**
527 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
528 * Each list holds references to all NetworkAgentInfos that are used to
529 * satisfy requests for that network type.
530 *
531 * This array is built out at startup such that an unsupported network
532 * doesn't get an ArrayList instance, making this a tristate:
533 * unsupported, supported but not active and active.
534 *
535 * The actual lists are populated when we scan the network types that
536 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 *
538 * Threading model:
539 * - addSupportedType() is only called in the constructor
540 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
541 * They are therefore not thread-safe with respect to each other.
542 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
543 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
544 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900546 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700547
548 public LegacyTypeTracker() {
549 mTypeLists = (ArrayList<NetworkAgentInfo>[])
550 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
551 }
552
553 public void addSupportedType(int type) {
554 if (mTypeLists[type] != null) {
555 throw new IllegalStateException(
556 "legacy list for type " + type + "already initialized");
557 }
558 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
559 }
560
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 public boolean isTypeSupported(int type) {
562 return isNetworkTypeValid(type) && mTypeLists[type] != null;
563 }
564
565 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900566 synchronized (mTypeLists) {
567 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
568 return mTypeLists[type].get(0);
569 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900571 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 }
573
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900578 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 }
581 }
582
583 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 public void add(int type, NetworkAgentInfo nai) {
585 if (!isTypeSupported(type)) {
586 return; // Invalid network type.
587 }
588 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
589
590 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
591 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 return;
593 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 synchronized (mTypeLists) {
595 list.add(nai);
596 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900597
598 // 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 +0900599 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900600 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
602 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700604 }
605
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900607 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list == null || list.isEmpty()) {
610 return;
611 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 synchronized (mTypeLists) {
615 if (!list.remove(nai)) {
616 return;
617 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 final DetailedState state = DetailedState.DISCONNECTED;
621
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(nai, state, type, wasDefault);
624 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626
627 if (!list.isEmpty() && wasFirstNetwork) {
628 if (DBG) log("Other network available for type " + type +
629 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700631 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
632 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 }
634 }
635
636 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
638 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700639 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
642 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700643
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 // send out another legacy broadcast - currently only used for suspend/unsuspend
645 // toggle
646 public void update(NetworkAgentInfo nai) {
647 final boolean isDefault = isDefaultNetwork(nai);
648 final DetailedState state = nai.networkInfo.getDetailedState();
649 for (int type = 0; type < mTypeLists.length; type++) {
650 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700651 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 final boolean isFirst = contains && (nai == list.get(0));
653 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700654 maybeLogBroadcast(nai, state, type, isDefault);
655 sendLegacyNetworkBroadcast(nai, state, type);
656 }
657 }
658 }
659
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 private String naiToString(NetworkAgentInfo nai) {
661 String name = (nai != null) ? nai.name() : "null";
662 String state = (nai.networkInfo != null) ?
663 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
664 "???/???";
665 return name + " " + state;
666 }
667
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println("mLegacyTypeTracker:");
670 pw.increaseIndent();
671 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 pw.println();
676 pw.println("Current state:");
677 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 synchronized (mTypeLists) {
679 for (int type = 0; type < mTypeLists.length; type++) {
680 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
681 for (NetworkAgentInfo nai : mTypeLists[type]) {
682 pw.println(type + " " + naiToString(nai));
683 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900684 }
685 }
686 pw.decreaseIndent();
687 pw.decreaseIndent();
688 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700689 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
692
Jeff Sharkey899223b2012-08-04 15:24:58 -0700693 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700694 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900695 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
696 }
697
698 @VisibleForTesting
699 protected ConnectivityService(Context context, INetworkManagementService netManager,
700 INetworkStatsService statsService, INetworkPolicyManager policyManager,
701 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800703
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900704 mSystemProperties = getSystemProperties();
705
Hugo Benichif9fdf872016-07-28 17:53:06 +0900706 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900707 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900708 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900709 mNetworkRequests.put(mDefaultRequest, defaultNRI);
710 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900711
712 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900713 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700714
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900715 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900716 mHandlerThread.start();
717 mHandler = new InternalHandler(mHandlerThread.getLooper());
718 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700719
Jeremy Joslin79294842014-12-03 17:15:28 -0800720 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
721 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
722
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900723 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900724
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700725 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700726 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800727 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900729 mPolicyManagerInternal = checkNotNull(
730 LocalServices.getService(NetworkPolicyManagerInternal.class),
731 "missing NetworkPolicyManagerInternal");
732
Jeff Sharkey82f85212012-08-24 11:17:25 -0700733 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700734 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700735
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900737 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 } catch (RemoteException e) {
739 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700740 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 }
742
743 final PowerManager powerManager = (PowerManager) context.getSystemService(
744 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
746 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
747 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800748 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751
Wink Saville51f456f2013-04-23 14:26:51 -0700752 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900753 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700754 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 String[] naStrings = context.getResources().getStringArray(
756 com.android.internal.R.array.networkAttributes);
757 for (String naString : naStrings) {
758 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700760 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700761 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700763 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765 }
Wink Saville51f456f2013-04-23 14:26:51 -0700766 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
767 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
768 n.type);
769 continue;
770 }
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
775 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700776 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700777
Wink Saville975c8482011-04-07 14:23:45 -0700778 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700779 mNetworksDefined++;
780 } catch(Exception e) {
781 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782 }
783 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700784
785 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
786 if (mNetConfigs[TYPE_VPN] == null) {
787 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
788 // don't need to add TYPE_VPN to mNetConfigs.
789 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
790 mNetworksDefined++; // used only in the log() statement below.
791 }
792
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900793 // Do the same for Ethernet, since it's often not specified in the configs, although many
794 // devices can use it via USB host adapters.
795 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
796 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
797 mNetworksDefined++;
798 }
799
Wink Saville5e56bc52013-07-29 15:00:57 -0700800 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700801
Robert Greenwalt50393202011-06-21 17:26:14 -0700802 mProtectedNetworks = new ArrayList<Integer>();
803 int[] protectedNetworks = context.getResources().getIntArray(
804 com.android.internal.R.array.config_protectedNetworks);
805 for (int p : protectedNetworks) {
806 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
807 mProtectedNetworks.add(p);
808 } else {
809 if (DBG) loge("Ignoring protectedNetwork " + p);
810 }
811 }
812
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900813 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
814 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700815
Erik Kline47222fc2017-04-30 19:36:15 +0900816 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800817
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700818 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
819
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700820 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700821 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100822 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700823 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700824 intentFilter.addAction(Intent.ACTION_USER_ADDED);
825 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000826 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700827 mContext.registerReceiverAsUser(
828 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000829 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
830 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900831
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700832 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700833 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700834 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700835 } catch (RemoteException e) {
836 loge("Error registering observer :" + e);
837 }
838
Erik Klineda4bfa82015-04-30 12:58:40 +0900839 mSettingsObserver = new SettingsObserver(mContext, mHandler);
840 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800841
John Spurlockbf991a82013-06-24 14:20:23 -0400842 mDataConnectionStats = new DataConnectionStats(mContext);
843 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400844
Jason Monkdecd2952013-10-10 14:02:51 -0400845 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700846
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400847 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900848
849 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900850 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
851 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900852
853 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
854 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
855 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
856 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
857 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
858 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
859 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900860
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900861 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900862 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900863 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700865
Erik Kline47222fc2017-04-30 19:36:15 +0900866 private Tethering makeTethering() {
867 // TODO: Move other elements into @Overridden getters.
868 final TetheringDependencies deps = new TetheringDependencies();
869 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
870 IoThread.get().getLooper(), new MockableSystemProperties(),
871 deps);
872 }
873
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900874 private NetworkRequest createInternetRequestForTransport(
875 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900876 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900877 netCap.addCapability(NET_CAPABILITY_INTERNET);
878 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 if (transportType > -1) {
880 netCap.addTransportType(transportType);
881 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900882 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900883 }
884
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900885 // Used only for testing.
886 // TODO: Delete this and either:
887 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
888 // changing ContentResolver to make registerContentObserver non-final).
889 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
890 // by subclassing SettingsObserver.
891 @VisibleForTesting
892 void updateMobileDataAlwaysOn() {
893 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
894 }
895
Erik Klineda4bfa82015-04-30 12:58:40 +0900896 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900897 final boolean enable = toBool(Settings.Global.getInt(
898 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900899 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
900 if (enable == isEnabled) {
901 return; // Nothing to do.
902 }
903
904 if (enable) {
905 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900906 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900907 } else {
908 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
909 }
910 }
911
912 private void registerSettingsCallbacks() {
913 // Watch for global HTTP proxy changes.
914 mSettingsObserver.observe(
915 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
916 EVENT_APPLY_GLOBAL_HTTP_PROXY);
917
918 // Watch for whether or not to keep mobile data always on.
919 mSettingsObserver.observe(
920 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
921 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
922 }
923
Robert Greenwalt34524f02014-05-18 16:22:10 -0700924 private synchronized int nextNetworkRequestId() {
925 return mNextNetworkRequestId++;
926 }
927
Paul Jensen67b0b072015-06-10 11:22:17 -0400928 @VisibleForTesting
929 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400930 synchronized (mNetworkForNetId) {
931 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
932 int netId = mNextNetId;
933 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
934 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500935 if (!mNetIdInUse.get(netId)) {
936 mNetIdInUse.put(netId, true);
937 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400938 }
939 }
940 }
941 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700942 }
943
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600944 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600946 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
947 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 state = nai.getNetworkState();
950 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600952 final NetworkInfo info = new NetworkInfo(networkType, 0,
953 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800954 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
955 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700956 final NetworkCapabilities capabilities = new NetworkCapabilities();
957 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
958 !info.isRoaming());
959 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600960 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600962 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600963 return state;
964 } else {
965 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400967 }
968
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
970 if (network == null) {
971 return null;
972 }
973 synchronized (mNetworkForNetId) {
974 return mNetworkForNetId.get(network.netId);
975 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900978 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +0900979 synchronized (mVpns) {
980 if (!mLockdownEnabled) {
981 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900982 Vpn vpn = mVpns.get(user);
983 if (vpn != null && vpn.appliesToUid(uid)) {
984 return vpn.getUnderlyingNetworks();
985 }
986 }
987 }
988 return null;
989 }
990
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400992 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800993
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900994 final Network[] networks = getVpnUnderlyingNetworks(uid);
995 if (networks != null) {
996 // getUnderlyingNetworks() returns:
997 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
998 // empty array => the VPN explicitly said "no default network".
999 // non-empty array => the VPN specified one or more default networks; we use the
1000 // first one.
1001 if (networks.length > 0) {
1002 nai = getNetworkAgentInfoForNetwork(networks[0]);
1003 } else {
1004 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001005 }
1006 }
1007
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001009 return nai.getNetworkState();
1010 } else {
1011 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001013 }
1014
1015 /**
1016 * Check if UID should be blocked from using the network with the given LinkProperties.
1017 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1019 boolean ignoreBlocked) {
1020 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001021 if (ignoreBlocked) {
1022 return false;
1023 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001024 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001025 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1026 if (isSystem(uid)) {
1027 return false;
1028 }
Robin Lee17e61832016-05-09 13:46:28 +01001029 synchronized (mVpns) {
1030 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1031 if (vpn != null && vpn.isBlockingUid(uid)) {
1032 return true;
1033 }
1034 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001035 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001036 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001037 }
1038
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001039 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001040 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1041 return;
1042 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001043 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001044 synchronized (mBlockedAppUids) {
1045 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001046 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001047 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001048 blocked = false;
1049 } else {
1050 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001051 }
1052 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001053 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1054 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1055 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001056 }
1057
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001059 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1060 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001061 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001062 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001063 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001064 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1065
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 }
Hugo Benichi69744342017-11-27 10:57:16 +09001069 synchronized (mVpns) {
1070 if (mLockdownTracker != null) {
1071 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1072 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001073 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 }
1075
1076 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 * Return NetworkInfo for the active (i.e., connected) network interface.
1078 * It is assumed that at most one network is active at a time. If more
1079 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001080 * @return the info for the active network, or {@code null} if none is
1081 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001083 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001085 enforceAccessPermission();
1086 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001088 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001089 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1090 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
1092
Paul Jensen31a94f42015-02-13 14:18:39 -05001093 @Override
1094 public Network getActiveNetwork() {
1095 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001097 }
1098
1099 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001100 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001101 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001103 }
1104
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001106 final int user = UserHandle.getUserId(uid);
1107 int vpnNetId = NETID_UNSET;
1108 synchronized (mVpns) {
1109 final Vpn vpn = mVpns.get(user);
1110 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1111 }
1112 NetworkAgentInfo nai;
1113 if (vpnNetId != NETID_UNSET) {
1114 synchronized (mNetworkForNetId) {
1115 nai = mNetworkForNetId.get(vpnNetId);
1116 }
1117 if (nai != null) return nai.network;
1118 }
1119 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 if (nai != null
1121 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1122 nai = null;
1123 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001124 return nai != null ? nai.network : null;
1125 }
1126
Lorenzo Colitti18660282016-07-04 12:55:44 +09001127 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001128 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1129 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 final int uid = Binder.getCallingUid();
1131 NetworkState state = getUnfilteredActiveNetworkState(uid);
1132 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001133 }
1134
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001135 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 }
1142
1143 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 public NetworkInfo getNetworkInfo(int networkType) {
1145 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001147 if (getVpnUnderlyingNetworks(uid) != null) {
1148 // A VPN is active, so we may need to return one of its underlying networks. This
1149 // information is not available in LegacyTypeTracker, so we have to get it from
1150 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001151 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001152 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001155 }
1156 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001157 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 return state.networkInfo;
1169 } else {
1170 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001172 }
1173
1174 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 public NetworkInfo[] getAllNetworkInfo() {
1176 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001177 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001178 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1179 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 NetworkInfo info = getNetworkInfo(networkType);
1181 if (info != null) {
1182 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001185 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001188 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001189 public Network getNetworkForType(int networkType) {
1190 enforceAccessPermission();
1191 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1193 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001194 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001195 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001197 }
1198
1199 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 public Network[] getAllNetworks() {
1201 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001203 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001205 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001207 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001208 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001209 }
1210
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001211 @Override
1212 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1213 // The basic principle is: if an app's traffic could possibly go over a
1214 // network, without the app doing anything multinetwork-specific,
1215 // (hence, by "default"), then include that network's capabilities in
1216 // the array.
1217 //
1218 // In the normal case, app traffic only goes over the system's default
1219 // network connection, so that's the only network returned.
1220 //
1221 // With a VPN in force, some app traffic may go into the VPN, and thus
1222 // over whatever underlying networks the VPN specifies, while other app
1223 // traffic may go over the system default network (e.g.: a split-tunnel
1224 // VPN, or an app disallowed by the VPN), so the set of networks
1225 // returned includes the VPN's underlying networks and the system
1226 // default.
1227 enforceAccessPermission();
1228
1229 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1230
1231 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001232 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001233 if (nc != null) {
1234 result.put(nai.network, nc);
1235 }
1236
Hugo Benichi69744342017-11-27 10:57:16 +09001237 synchronized (mVpns) {
1238 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001239 Vpn vpn = mVpns.get(userId);
1240 if (vpn != null) {
1241 Network[] networks = vpn.getUnderlyingNetworks();
1242 if (networks != null) {
1243 for (Network network : networks) {
1244 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001245 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001246 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001247 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001248 }
1249 }
1250 }
1251 }
1252 }
1253 }
1254
1255 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1256 out = result.values().toArray(out);
1257 return out;
1258 }
1259
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001260 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001261 public boolean isNetworkSupported(int networkType) {
1262 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001263 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001264 }
1265
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001266 /**
1267 * Return LinkProperties for the active (i.e., connected) default
1268 * network interface. It is assumed that at most one default network
1269 * is active at a time. If more than one is active, it is indeterminate
1270 * which will be returned.
1271 * @return the ip properties for the active network, or {@code null} if
1272 * none is active
1273 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001274 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001275 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001276 enforceAccessPermission();
1277 final int uid = Binder.getCallingUid();
1278 NetworkState state = getUnfilteredActiveNetworkState(uid);
1279 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 }
1281
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001282 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001283 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001284 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001285 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1286 if (nai != null) {
1287 synchronized (nai) {
1288 return new LinkProperties(nai.linkProperties);
1289 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001290 }
1291 return null;
1292 }
1293
Robert Greenwalt12e67352014-05-13 21:41:06 -07001294 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001295 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001296 public LinkProperties getLinkProperties(Network network) {
1297 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001298 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1299 }
1300
1301 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1302 if (nai == null) {
1303 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001304 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001305 synchronized (nai) {
1306 return new LinkProperties(nai.linkProperties);
1307 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001308 }
1309
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001310 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001311 if (nai != null) {
1312 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001313 if (nai.networkCapabilities != null) {
1314 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001315 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001316 }
1317 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001318 return null;
1319 }
1320
1321 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001322 public NetworkCapabilities getNetworkCapabilities(Network network) {
1323 enforceAccessPermission();
1324 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1325 }
1326
1327 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001328 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001329 // Require internal since we're handing out IMSI details
1330 enforceConnectivityInternalPermission();
1331
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001332 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001333 for (Network network : getAllNetworks()) {
1334 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1335 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001336 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001337 }
1338 }
1339 return result.toArray(new NetworkState[result.size()]);
1340 }
1341
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001342 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001343 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001344 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001345 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1346 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1347 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001348 }
1349
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001350 @Override
1351 public boolean isActiveNetworkMetered() {
1352 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001353
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001354 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1355 if (caps != null) {
1356 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1357 } else {
1358 // Always return the most conservative value
1359 return true;
1360 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001361 }
1362
Jeff Sharkey216c1812012-08-05 14:29:23 -07001363 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1364 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001365 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001366 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001367 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001368 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001369 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001370
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001371 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 * Ensure that a network route exists to deliver traffic to the specified
1373 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001374 * @param networkType the type of the network over which traffic to the
1375 * specified host is to be routed
1376 * @param hostAddress the IP address of the host to which the route is
1377 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 * @return {@code true} on success, {@code false} on failure
1379 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001380 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001381 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001383 if (mProtectedNetworks.contains(networkType)) {
1384 enforceConnectivityInternalPermission();
1385 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001386
Chad Brubakerc0234532014-02-14 13:24:29 -08001387 InetAddress addr;
1388 try {
1389 addr = InetAddress.getByAddress(hostAddress);
1390 } catch (UnknownHostException e) {
1391 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1392 return false;
1393 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001396 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 return false;
1398 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001399
1400 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1401 if (nai == null) {
1402 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1403 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1404 } else {
1405 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1406 }
1407 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001408 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001410 DetailedState netState;
1411 synchronized (nai) {
1412 netState = nai.networkInfo.getDetailedState();
1413 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001414
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001415 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001416 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001417 log("requestRouteToHostAddress on down network "
1418 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001419 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001420 }
1421 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001423
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001424 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001425 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001426 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001427 LinkProperties lp;
1428 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001429 synchronized (nai) {
1430 lp = nai.linkProperties;
1431 netId = nai.network.netId;
1432 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001433 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001434 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1435 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001436 } finally {
1437 Binder.restoreCallingIdentity(token);
1438 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001439 }
1440
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001441 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001442 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001443 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001444 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001445 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001446 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001447 if (bestRoute.getGateway().equals(addr)) {
1448 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001449 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 } else {
1451 // if we will connect to this through another route, add a direct route
1452 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001453 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001454 }
1455 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001456 if (DBG) log("Adding legacy route " + bestRoute +
1457 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001458 try {
1459 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1460 } catch (Exception e) {
1461 // never crash - catch them all
1462 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001463 return false;
1464 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001465 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001468 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001469 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001470 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001471 // TODO: notify UID when it has requested targeted updates
1472 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001473 @Override
1474 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001475 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001476 @Override
1477 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001478 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001479 if (restrictBackground) {
1480 log("onRestrictBackgroundChanged(true): disabling tethering");
1481 mTethering.untetherAll();
1482 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001483 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001484 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001485 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001486 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 };
1488
Robin Lee3b3dd942015-05-12 18:14:58 +01001489 /**
1490 * Require that the caller is either in the same user or has appropriate permission to interact
1491 * across users.
1492 *
1493 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1494 */
1495 private void enforceCrossUserPermission(int userId) {
1496 if (userId == UserHandle.getCallingUserId()) {
1497 // Not a cross-user call.
1498 return;
1499 }
1500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1502 "ConnectivityService");
1503 }
1504
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001505 private void enforceInternetPermission() {
1506 mContext.enforceCallingOrSelfPermission(
1507 android.Manifest.permission.INTERNET,
1508 "ConnectivityService");
1509 }
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001512 mContext.enforceCallingOrSelfPermission(
1513 android.Manifest.permission.ACCESS_NETWORK_STATE,
1514 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
1517 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001518 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520
Charles Hea0a87e82017-05-15 17:07:18 +01001521 private void enforceSettingsPermission() {
1522 mContext.enforceCallingOrSelfPermission(
1523 android.Manifest.permission.NETWORK_SETTINGS,
1524 "ConnectivityService");
1525 }
1526
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001527 private void enforceTetherAccessPermission() {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.ACCESS_NETWORK_STATE,
1530 "ConnectivityService");
1531 }
1532
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001533 private void enforceConnectivityInternalPermission() {
1534 mContext.enforceCallingOrSelfPermission(
1535 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1536 "ConnectivityService");
1537 }
1538
Hugo Benichi514da602016-07-19 15:59:27 +09001539 private void enforceConnectivityRestrictedNetworksPermission() {
1540 try {
1541 mContext.enforceCallingOrSelfPermission(
1542 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1543 "ConnectivityService");
1544 return;
1545 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1546 enforceConnectivityInternalPermission();
1547 }
1548
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001549 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001550 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001551 }
1552
Lorenzo Colitti18660282016-07-04 12:55:44 +09001553 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001554 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001555 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001556 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001557 }
1558
1559 private void sendInetConditionBroadcast(NetworkInfo info) {
1560 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1561 }
1562
Wink Saville628b0852011-08-04 15:01:58 -07001563 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001564 synchronized (mVpns) {
1565 if (mLockdownTracker != null) {
1566 info = new NetworkInfo(info);
1567 mLockdownTracker.augmentNetworkInfo(info);
1568 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001569 }
1570
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001571 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001572 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001573 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 if (info.isFailover()) {
1575 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1576 info.setFailover(false);
1577 }
1578 if (info.getReason() != null) {
1579 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1580 }
1581 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001582 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1583 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001585 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001586 return intent;
1587 }
1588
1589 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1590 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1591 }
1592
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001593 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001594 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1595 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1596 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001597 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001598 final long ident = Binder.clearCallingIdentity();
1599 try {
1600 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1601 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1602 } finally {
1603 Binder.restoreCallingIdentity(ident);
1604 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001605 }
1606
Mike Lockwood0f79b542009-08-14 14:18:49 -04001607 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001608 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001609 if (!mSystemReady) {
1610 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001612 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001613 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001614 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001615 }
1616
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001617 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001618 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001619 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001620 final NetworkInfo ni = intent.getParcelableExtra(
1621 ConnectivityManager.EXTRA_NETWORK_INFO);
1622 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1623 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1624 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001625 } else {
1626 BroadcastOptions opts = BroadcastOptions.makeBasic();
1627 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1628 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001629 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001630 final IBatteryStats bs = BatteryStatsService.getService();
1631 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001632 bs.noteConnectivityChanged(intent.getIntExtra(
1633 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1634 ni != null ? ni.getState().toString() : "?");
1635 } catch (RemoteException e) {
1636 }
1637 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001638 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001639 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001640 } finally {
1641 Binder.restoreCallingIdentity(ident);
1642 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001643 }
1644 }
1645
1646 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001647 loadGlobalProxy();
1648
Hugo Benichi20035e02017-04-26 14:53:28 +09001649 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001650 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001651 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001652 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001653 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001654 }
1655 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001656 // load the global proxy at startup
1657 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001658
Robin Lee244ce8e2016-01-05 18:03:46 +00001659 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1660 // for user to unlock device too.
1661 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001662
Erik Klineda4bfa82015-04-30 12:58:40 +09001663 // Configure whether mobile data is always on.
1664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1665
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001666 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001667
1668 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 }
1670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001673 *
1674 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001675 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001676 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1678 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001679
1680 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001682
Robert Greenwalt7b816022014-04-18 15:25:25 -07001683 if (networkAgent.networkCapabilities.hasTransport(
1684 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001685 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1686 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001687 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001688 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001689 } else if (networkAgent.networkCapabilities.hasTransport(
1690 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001691 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1692 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001693 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001695 } else {
1696 // do not track any other networks
1697 timeout = 0;
1698 }
1699
Robert Greenwalt7b816022014-04-18 15:25:25 -07001700 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001701 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001702 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001703 } catch (Exception e) {
1704 // You shall not crash!
1705 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001706 }
1707 }
1708 }
1709
1710 /**
1711 * Remove data activity tracking when network disconnects.
1712 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1714 final String iface = networkAgent.linkProperties.getInterfaceName();
1715 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001716
Robert Greenwalt7b816022014-04-18 15:25:25 -07001717 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1718 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001719 try {
1720 // the call fails silently if no idletimer setup for this interface
1721 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001722 } catch (Exception e) {
1723 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001724 }
1725 }
1726 }
1727
1728 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001729 * Reads the network specific MTU size from reources.
1730 * and set it on it's iface.
1731 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1733 final String iface = newLp.getInterfaceName();
1734 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001735 if (oldLp == null && mtu == 0) {
1736 // Silently ignore unset MTU value.
1737 return;
1738 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1740 if (VDBG) log("identical MTU - not setting");
1741 return;
1742 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001743 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001744 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 return;
1746 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001747
w1997615afd812014-08-05 15:18:11 -07001748 // Cannot set MTU without interface name
1749 if (TextUtils.isEmpty(iface)) {
1750 loge("Setting MTU size with null iface.");
1751 return;
1752 }
1753
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001755 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 mNetd.setMtu(iface, mtu);
1757 } catch (Exception e) {
1758 Slog.e(TAG, "exception in setMtu()" + e);
1759 }
1760 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001761
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001762 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001763 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1764
1765 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001766 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001767 protected MockableSystemProperties getSystemProperties() {
1768 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001769 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001770
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001771 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1772 if (isDefaultNetwork(nai) == false) {
1773 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001774 }
1775
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001776 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1777 String[] values = null;
1778 if (tcpBufferSizes != null) {
1779 values = tcpBufferSizes.split(",");
1780 }
1781
1782 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001783 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001784 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1785 values = tcpBufferSizes.split(",");
1786 }
1787
1788 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1789
1790 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001791 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001792
1793 final String prefix = "/sys/kernel/ipv4/tcp_";
1794 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1795 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1796 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1797 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1798 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1799 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1800 mCurrentTcpBufferSizes = tcpBufferSizes;
1801 } catch (IOException e) {
1802 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001803 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001804
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001805 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001806 Settings.Global.TCP_DEFAULT_INIT_RWND,
1807 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001808 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1809 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001810 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001811 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001812 }
1813
Mattias Falk8b47b362011-08-23 14:15:13 +02001814 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001815 /*
1816 * Tell the VMs to toss their DNS caches
1817 */
1818 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1819 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001820 /*
1821 * Connectivity events can happen before boot has completed ...
1822 */
1823 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001824 final long ident = Binder.clearCallingIdentity();
1825 try {
1826 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1827 } finally {
1828 Binder.restoreCallingIdentity(ident);
1829 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001830 }
1831
Robert Greenwalt562cc542014-05-15 18:07:26 -07001832 @Override
1833 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001834 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001835 NETWORK_RESTORE_DELAY_PROP_NAME);
1836 if(restoreDefaultNetworkDelayStr != null &&
1837 restoreDefaultNetworkDelayStr.length() != 0) {
1838 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001839 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001840 } catch (NumberFormatException e) {
1841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001843 // if the system property isn't set, use the value for the apn type
1844 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1845
1846 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1847 (mNetConfigs[networkType] != null)) {
1848 ret = mNetConfigs[networkType].restoreTime;
1849 }
1850 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
1852
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001853 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001854 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001855 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001856 }
1857 return false;
1858 }
1859
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001860 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1861 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1862 final long DIAG_TIME_MS = 5000;
1863 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1864 // Start gathering diagnostic information.
1865 netDiags.add(new NetworkDiagnostics(
1866 nai.network,
1867 new LinkProperties(nai.linkProperties), // Must be a copy.
1868 DIAG_TIME_MS));
1869 }
1870
1871 for (NetworkDiagnostics netDiag : netDiags) {
1872 pw.println();
1873 netDiag.waitForMeasurements();
1874 netDiag.dump(pw);
1875 }
1876 }
1877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001879 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1880 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001881 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001882
Erik Kline7747fd42017-05-12 16:52:48 +09001883 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001884 dumpNetworkDiagnostics(pw);
1885 return;
Erik Klineee363c42017-05-29 09:11:03 +09001886 } else if (argsContain(args, TETHERING_ARG)) {
1887 mTethering.dump(fd, pw, args);
1888 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001889 }
Erik Kline379747a2015-06-05 17:47:34 +09001890
Lorenzo Colittie3805462015-06-03 11:18:24 +09001891 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001892 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001893 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001894 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001895 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001896 pw.println();
1897
Paul Jensen85cf78e2015-06-25 13:25:07 -04001898 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001899 pw.print("Active default network: ");
1900 if (defaultNai == null) {
1901 pw.println("none");
1902 } else {
1903 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001905 pw.println();
1906
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001907 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001908 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001909 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1910 pw.println(nai.toString());
1911 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001912 pw.println(String.format(
1913 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1914 nai.numForegroundNetworkRequests(),
1915 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1916 nai.numBackgroundNetworkRequests(),
1917 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001918 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001919 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1920 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001921 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 pw.decreaseIndent();
1923 pw.println("Lingered:");
1924 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001925 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 pw.decreaseIndent();
1927 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001928 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001929 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001930 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001931
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001932 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001933 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001934 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1935 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001936 }
1937 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001938 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001939
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001940 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001941
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001942 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001943 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001944
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001945 pw.println();
1946 mKeepaliveTracker.dump(pw);
1947
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001948 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001949 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001950
Erik Kline7747fd42017-05-12 16:52:48 +09001951 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001952 pw.println();
1953 synchronized (mValidationLogs) {
1954 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001955 for (ValidationLog p : mValidationLogs) {
1956 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001957 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001958 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001959 pw.decreaseIndent();
1960 }
1961 }
Erik Kline7523eb32015-07-09 18:24:03 +09001962
1963 pw.println();
1964 pw.println("mNetworkRequestInfoLogs (most recent first):");
1965 pw.increaseIndent();
1966 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1967 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001968
1969 pw.println();
1970 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1971 pw.increaseIndent();
1972 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1973 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001974
1975 pw.println();
1976 pw.println("NetTransition WakeLock activity (most recent first):");
1977 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001978 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1979 pw.println("total releases: " + mTotalWakelockReleases);
1980 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1981 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1982 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1983 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1984 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1985 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001986 mWakelockLogs.reverseDump(fd, pw, args);
1987 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
1990
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001991 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001992 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001993 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001994 if (officialNai != null && officialNai.equals(nai)) return true;
1995 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001996 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001997 " - " + nai);
1998 }
1999 return false;
2000 }
2001
Robert Greenwalt42acef32009-08-12 16:08:25 -07002002 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002003 private class NetworkStateTrackerHandler extends Handler {
2004 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002005 super(looper);
2006 }
2007
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002008 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 default:
2011 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002012 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002013 handleAsyncChannelHalfConnect(msg);
2014 break;
2015 }
2016 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2017 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2018 if (nai != null) nai.asyncChannel.disconnect();
2019 break;
2020 }
2021 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2022 handleAsyncChannelDisconnected(msg);
2023 break;
2024 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002025 }
2026 return true;
2027 }
2028
2029 private void maybeHandleNetworkAgentMessage(Message msg) {
2030 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2031 if (nai == null) {
2032 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002033 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002034 }
2035 return;
2036 }
2037
2038 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002040 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2041 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002042 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2043 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002045 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002046 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002047 break;
2048 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002049 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002050 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002051 break;
2052 }
2053 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002054 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002055 updateNetworkInfo(nai, info);
2056 break;
2057 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002058 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002059 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002060 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002061 break;
2062 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002063 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002064 try {
2065 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002066 } catch (Exception e) {
2067 // Never crash!
2068 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002069 }
2070 break;
2071 }
2072 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002073 try {
2074 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002075 } catch (Exception e) {
2076 // Never crash!
2077 loge("Exception in removeVpnUidRanges: " + e);
2078 }
2079 break;
2080 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002081 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002082 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2083 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002084 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002085 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002086 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002087 break;
2088 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002089 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002090 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2091 break;
2092 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002093 }
2094 }
2095
2096 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2097 switch (msg.what) {
2098 default:
2099 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002100 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002101 final NetworkAgentInfo nai;
2102 synchronized (mNetworkForNetId) {
2103 nai = mNetworkForNetId.get(msg.arg2);
2104 }
2105 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002106 final boolean valid =
2107 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002108 final boolean wasValidated = nai.lastValidated;
Hugo Benichi380a0632017-10-20 09:25:29 +09002109 final boolean wasDefault = isDefaultNetwork(nai);
Paul Jensen232437312016-04-06 09:51:26 -04002110 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2111 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002112 if (valid != nai.lastValidated) {
Hugo Benichi380a0632017-10-20 09:25:29 +09002113 if (wasDefault) {
2114 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2115 SystemClock.elapsedRealtime(), valid);
2116 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04002117 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002118 nai.lastValidated = valid;
2119 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002120 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002121 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2122 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002123 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002124 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002125 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002126 Bundle redirectUrlBundle = new Bundle();
2127 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002128 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002129 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002130 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002131 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002132 if (wasValidated && !nai.lastValidated) {
2133 handleNetworkUnvalidated(nai);
2134 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002135 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002136 break;
2137 }
Paul Jensen869868be2014-05-15 10:33:05 -04002138 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002139 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002140 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002141 final NetworkAgentInfo nai;
2142 synchronized (mNetworkForNetId) {
2143 nai = mNetworkForNetId.get(netId);
2144 }
Calvin Onbe96da12016-10-11 15:10:46 -07002145 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002146 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002147 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002148 nai.lastCaptivePortalDetected = visible;
2149 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002150 if (nai.lastCaptivePortalDetected &&
2151 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2152 if (DBG) log("Avoiding captive portal network: " + nai.name());
2153 nai.asyncChannel.sendMessage(
2154 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2155 teardownUnneededNetwork(nai);
2156 break;
2157 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002158 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002159 }
2160 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002161 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002162 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002163 if (nai == null) {
2164 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2165 break;
2166 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002167 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002168 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002169 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002170 }
Paul Jensen869868be2014-05-15 10:33:05 -04002171 }
Paul Jensen869868be2014-05-15 10:33:05 -04002172 break;
2173 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002174 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 return true;
2176 }
2177
Calvin Onbe96da12016-10-11 15:10:46 -07002178 private int getCaptivePortalMode() {
2179 return Settings.Global.getInt(mContext.getContentResolver(),
2180 Settings.Global.CAPTIVE_PORTAL_MODE,
2181 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2182 }
2183
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002184 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2185 switch (msg.what) {
2186 default:
2187 return false;
2188 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2189 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2190 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2191 handleLingerComplete(nai);
2192 }
2193 break;
2194 }
2195 }
2196 return true;
2197 }
2198
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002199 @Override
2200 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002201 if (!maybeHandleAsyncChannelMessage(msg) &&
2202 !maybeHandleNetworkMonitorMessage(msg) &&
2203 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002204 maybeHandleNetworkAgentMessage(msg);
2205 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002206 }
2207 }
2208
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002209 private void updateLingerState(NetworkAgentInfo nai, long now) {
2210 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2211 // 2. If the network was lingering and there are now requests, unlinger it.
2212 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2213 // one lingered request, start lingering.
2214 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002215 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002216 if (DBG) log("Unlingering " + nai.name());
2217 nai.unlinger();
2218 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002219 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002220 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002221 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002222 nai.linger();
2223 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2224 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2225 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002226 }
2227
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 private void handleAsyncChannelHalfConnect(Message msg) {
2229 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002230 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002231 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2232 if (VDBG) log("NetworkFactory connected");
2233 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002234 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002235 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002236 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002237 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002238 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002239 }
2240 } else {
2241 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002242 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002243 }
2244 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2245 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2246 if (VDBG) log("NetworkAgent connected");
2247 // A network agent has requested a connection. Establish the connection.
2248 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2249 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2250 } else {
2251 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002252 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002253 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002254 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002255 synchronized (mNetworkForNetId) {
2256 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002257 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002258 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002259 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002260 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002262 }
2263 }
2264 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002265
Robert Greenwalt7b816022014-04-18 15:25:25 -07002266 private void handleAsyncChannelDisconnected(Message msg) {
2267 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2268 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002269 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002270 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002271 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002272 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002273 // TODO - if we move the logic to the network agent (have them disconnect
2274 // because they lost all their requests or because their score isn't good)
2275 // then they would disconnect organically, report their new state and then
2276 // disconnect the channel.
2277 if (nai.networkInfo.isConnected()) {
2278 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2279 null, null);
2280 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002281 final boolean wasDefault = isDefaultNetwork(nai);
2282 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002283 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002284 // Log default network disconnection before required book-keeping.
2285 // Let rematchAllNetworksAndRequests() below record a new default network event
2286 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2287 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002288 long now = SystemClock.elapsedRealtime();
2289 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002290 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002291 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002292 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2293 // by other networks that are already connected. Perhaps that can be done by
2294 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2295 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002296 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002297 mKeepaliveTracker.handleStopAllKeepalives(nai,
2298 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002299 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2300 // Disable wakeup packet monitoring for each interface.
2301 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2302 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002303 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002304 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002305 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002306 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002307 // Remove the NetworkAgent, but don't mark the netId as
2308 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002309 mNetworkForNetId.remove(nai.network.netId);
2310 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002311 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002312 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2313 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002314 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002316 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 sendUpdatedScoreToFactories(request, 0);
2318 }
2319 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002320 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002321 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002322 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002323 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002324 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002325 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002326 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002327 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002328 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002329 if (nai.created) {
2330 // Tell netd to clean up the configuration for this network
2331 // (routing rules, DNS, etc).
2332 // This may be slow as it requires a lot of netd shelling out to ip and
2333 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2334 // after we've rematched networks with requests which should make a potential
2335 // fallback network the default or requested a new network from the
2336 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2337 // long time.
2338 try {
2339 mNetd.removeNetwork(nai.network.netId);
2340 } catch (Exception e) {
2341 loge("Exception removing network: " + e);
2342 }
2343 }
2344 synchronized (mNetworkForNetId) {
2345 mNetIdInUse.delete(nai.network.netId);
2346 }
2347 } else {
2348 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2349 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002350 }
2351 }
2352
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002353 // If this method proves to be too slow then we can maintain a separate
2354 // pendingIntent => NetworkRequestInfo map.
2355 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2356 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2357 Intent intent = pendingIntent.getIntent();
2358 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2359 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2360 if (existingPendingIntent != null &&
2361 existingPendingIntent.getIntent().filterEquals(intent)) {
2362 return entry.getValue();
2363 }
2364 }
2365 return null;
2366 }
2367
2368 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2369 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2370
2371 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2372 if (existingRequest != null) { // remove the existing request.
2373 if (DBG) log("Replacing " + existingRequest.request + " with "
2374 + nri.request + " because their intents matched.");
2375 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2376 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002377 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002378 }
2379
Erik Klineda4bfa82015-04-30 12:58:40 +09002380 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002381 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002382 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002383 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002384 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002385 if (nri.request.networkCapabilities.hasSignalStrength() &&
2386 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2387 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002388 }
2389 }
2390 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002391 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002392 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002393 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002394 }
2395 }
2396
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002397 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2398 int callingUid) {
2399 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2400 if (nri != null) {
2401 handleReleaseNetworkRequest(nri.request, callingUid);
2402 }
2403 }
2404
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002405 // Determines whether the network is the best (or could become the best, if it validated), for
2406 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2407 // on the value of reason:
2408 //
2409 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2410 // then it should be torn down.
2411 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2412 // then it should be lingered.
2413 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2414 final int numRequests;
2415 switch (reason) {
2416 case TEARDOWN:
2417 numRequests = nai.numRequestNetworkRequests();
2418 break;
2419 case LINGER:
2420 numRequests = nai.numForegroundNetworkRequests();
2421 break;
2422 default:
2423 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2424 return true;
2425 }
2426
2427 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002428 return false;
2429 }
Paul Jensene0988542015-06-25 15:30:08 -04002430 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002431 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2432 // Background requests don't affect lingering.
2433 continue;
2434 }
2435
Paul Jensene0988542015-06-25 15:30:08 -04002436 // If this Network is already the highest scoring Network for a request, or if
2437 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002438 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002439 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002440 // Note that this catches two important cases:
2441 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2442 // is currently satisfying the request. This is desirable when
2443 // cellular ends up validating but WiFi does not.
2444 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002445 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002446 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002447 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002448 nai.getCurrentScoreAsValidated())) {
2449 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002450 }
2451 }
Paul Jensene0988542015-06-25 15:30:08 -04002452 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002453 }
2454
Erik Klineacdd6392016-07-07 16:50:58 +09002455 private NetworkRequestInfo getNriForAppRequest(
2456 NetworkRequest request, int callingUid, String requestedOperation) {
2457 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2458
Robert Greenwalt9258c642014-03-26 16:47:06 -07002459 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002460 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002461 log(String.format("UID %d attempted to %s for unowned request %s",
2462 callingUid, requestedOperation, nri));
2463 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002464 }
Erik Klineacdd6392016-07-07 16:50:58 +09002465 }
2466
2467 return nri;
2468 }
2469
Erik Kline57faba92015-11-25 12:49:38 +09002470 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002471 if (mNetworkRequests.get(nri.request) == null) {
2472 return;
Erik Kline57faba92015-11-25 12:49:38 +09002473 }
Hugo Benichicd952782017-09-20 11:20:14 +09002474 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002475 return;
2476 }
2477 if (VDBG || (DBG && nri.request.isRequest())) {
2478 log("releasing " + nri.request + " (timeout)");
2479 }
2480 handleRemoveNetworkRequest(nri);
2481 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002482 }
2483
Erik Klineacdd6392016-07-07 16:50:58 +09002484 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002485 final NetworkRequestInfo nri =
2486 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2487 if (nri == null) {
2488 return;
Erik Kline57faba92015-11-25 12:49:38 +09002489 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002490 if (VDBG || (DBG && nri.request.isRequest())) {
2491 log("releasing " + nri.request + " (release request)");
2492 }
2493 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002494 }
Erik Klineacdd6392016-07-07 16:50:58 +09002495
Hugo Benichidba33db2017-03-23 22:40:44 +09002496 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002497 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002498 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002499 synchronized (mUidToNetworkRequestCount) {
2500 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2501 if (requests < 1) {
2502 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2503 nri.mUid);
2504 } else if (requests == 1) {
2505 mUidToNetworkRequestCount.removeAt(
2506 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2507 } else {
2508 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2509 }
2510 }
2511 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2512 if (nri.request.isRequest()) {
2513 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002514 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002515 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002516 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002517 nai.removeRequest(nri.request.requestId);
2518 if (VDBG) {
2519 log(" Removing from current network " + nai.name() +
2520 ", leaving " + nai.numNetworkRequests() + " requests.");
2521 }
2522 // If there are still lingered requests on this network, don't tear it down,
2523 // but resume lingering instead.
2524 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002525 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002526 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2527 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002528 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002529 wasKept = true;
2530 }
Hugo Benichicd952782017-09-20 11:20:14 +09002531 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002532 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2533 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002534 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002535 }
Erik Klineacdd6392016-07-07 16:50:58 +09002536 }
2537
2538 // TODO: remove this code once we know that the Slog.wtf is never hit.
2539 //
2540 // Find all networks that are satisfying this request and remove the request
2541 // from their request lists.
2542 // TODO - it's my understanding that for a request there is only a single
2543 // network satisfying it, so this loop is wasteful
2544 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2545 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2546 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2547 otherNai.name() + ", but mNetworkAgentInfos says " +
2548 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002549 }
2550 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002551
Erik Klineacdd6392016-07-07 16:50:58 +09002552 // Maintain the illusion. When this request arrived, we might have pretended
2553 // that a network connected to serve it, even though the network was already
2554 // connected. Now that this request has gone away, we might have to pretend
2555 // that the network disconnected. LegacyTypeTracker will generate that
2556 // phantom disconnect for this type.
2557 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2558 boolean doRemove = true;
2559 if (wasKept) {
2560 // check if any of the remaining requests for this network are for the
2561 // same legacy type - if so, don't remove the nai
2562 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2563 NetworkRequest otherRequest = nai.requestAt(i);
2564 if (otherRequest.legacyType == nri.request.legacyType &&
2565 otherRequest.isRequest()) {
2566 if (DBG) log(" still have other legacy request - leaving");
2567 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002568 }
2569 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002570 }
2571
Erik Klineacdd6392016-07-07 16:50:58 +09002572 if (doRemove) {
2573 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002574 }
2575 }
Erik Klineacdd6392016-07-07 16:50:58 +09002576
2577 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2578 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2579 nri.request);
2580 }
2581 } else {
2582 // listens don't have a singular affectedNetwork. Check all networks to see
2583 // if this listen request applies and remove it.
2584 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2585 nai.removeRequest(nri.request.requestId);
2586 if (nri.request.networkCapabilities.hasSignalStrength() &&
2587 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2588 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2589 }
2590 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002591 }
2592 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002593
Lorenzo Colitti18660282016-07-04 12:55:44 +09002594 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002595 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2596 enforceConnectivityInternalPermission();
2597 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002598 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002599 }
2600
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002601 @Override
2602 public void setAvoidUnvalidated(Network network) {
2603 enforceConnectivityInternalPermission();
2604 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2605 }
2606
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002607 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2608 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2609 " accept=" + accept + " always=" + always);
2610
2611 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2612 if (nai == null) {
2613 // Nothing to do.
2614 return;
2615 }
2616
2617 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002618 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002619 return;
2620 }
2621
2622 if (!nai.networkMisc.explicitlySelected) {
2623 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2624 }
2625
2626 if (accept != nai.networkMisc.acceptUnvalidated) {
2627 int oldScore = nai.getCurrentScore();
2628 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002629 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002630 sendUpdatedScoreToFactories(nai);
2631 }
2632
2633 if (always) {
2634 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002635 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002636 }
2637
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002638 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002639 // Tell the NetworkAgent to not automatically reconnect to the network.
2640 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2641 // Teardown the nework.
2642 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002643 }
2644
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002645 }
2646
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002647 private void handleSetAvoidUnvalidated(Network network) {
2648 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2649 if (nai == null || nai.lastValidated) {
2650 // Nothing to do. The network either disconnected or revalidated.
2651 return;
2652 }
2653 if (!nai.avoidUnvalidated) {
2654 int oldScore = nai.getCurrentScore();
2655 nai.avoidUnvalidated = true;
2656 rematchAllNetworksAndRequests(nai, oldScore);
2657 sendUpdatedScoreToFactories(nai);
2658 }
2659 }
2660
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002661 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002662 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002663 mHandler.sendMessageDelayed(
2664 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2665 PROMPT_UNVALIDATED_DELAY_MS);
2666 }
2667
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002668 @Override
2669 public void startCaptivePortalApp(Network network) {
2670 enforceConnectivityInternalPermission();
2671 mHandler.post(() -> {
2672 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2673 if (nai == null) return;
2674 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2675 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2676 });
2677 }
2678
Hugo Benichic8e9e122016-09-14 23:23:08 +00002679 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002680 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002681 }
2682
Erik Kline065ab6e2016-10-02 18:02:14 +09002683 private void rematchForAvoidBadWifiUpdate() {
2684 rematchAllNetworksAndRequests(null, 0);
2685 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2686 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2687 sendUpdatedScoreToFactories(nai);
2688 }
2689 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002690 }
2691
Erik Kline065ab6e2016-10-02 18:02:14 +09002692 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002693 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002694 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002695 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002696 if (!configRestrict) {
2697 pw.println("Bad Wi-Fi avoidance: unrestricted");
2698 return;
2699 }
2700
2701 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2702 pw.increaseIndent();
2703 pw.println("Config restrict: " + configRestrict);
2704
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002705 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002706 String description;
2707 // Can't use a switch statement because strings are legal case labels, but null is not.
2708 if ("0".equals(value)) {
2709 description = "get stuck";
2710 } else if (value == null) {
2711 description = "prompt";
2712 } else if ("1".equals(value)) {
2713 description = "avoid";
2714 } else {
2715 description = value + " (?)";
2716 }
2717 pw.println("User setting: " + description);
2718 pw.println("Network overrides:");
2719 pw.increaseIndent();
2720 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2721 if (nai.avoidUnvalidated) {
2722 pw.println(nai.name());
2723 }
2724 }
2725 pw.decreaseIndent();
2726 pw.decreaseIndent();
2727 }
2728
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002729 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2730 final String action;
2731 switch (type) {
2732 case NO_INTERNET:
2733 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2734 break;
2735 case LOST_INTERNET:
2736 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2737 break;
2738 default:
2739 Slog.wtf(TAG, "Unknown notification type " + type);
2740 return;
2741 }
2742
2743 Intent intent = new Intent(action);
2744 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2745 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2746 intent.setClassName("com.android.settings",
2747 "com.android.settings.wifi.WifiNoInternetDialog");
2748
2749 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2750 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2751 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2752 }
2753
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002754 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002755 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002756 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2757
2758 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2759 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002760 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002761 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002762 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2763 return;
2764 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002765 showValidationNotification(nai, NotificationType.NO_INTERNET);
2766 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002767
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002768 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2769 NetworkCapabilities nc = nai.networkCapabilities;
2770 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002771
Erik Kline065ab6e2016-10-02 18:02:14 +09002772 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002773 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002774 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2775 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002776 }
2777
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002778 @Override
2779 public int getMultipathPreference(Network network) {
2780 enforceAccessPermission();
2781
2782 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002783 if (nai != null && nai.networkCapabilities
2784 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002785 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2786 }
2787
2788 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2789 }
2790
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002791 private class InternalHandler extends Handler {
2792 public InternalHandler(Looper looper) {
2793 super(looper);
2794 }
2795
2796 @Override
2797 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002798 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002799 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002800 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002801 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002802 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002803 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002804 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002805 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002806 break;
2807 }
Jason Monkdecd2952013-10-10 14:02:51 -04002808 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002809 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002810 break;
2811 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002812 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002813 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2814 break;
2815 }
2816 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2817 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002818 break;
2819 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002820 case EVENT_REGISTER_NETWORK_AGENT: {
2821 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2822 break;
2823 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002824 case EVENT_REGISTER_NETWORK_REQUEST:
2825 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002826 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002827 break;
2828 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002829 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2830 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002831 handleRegisterNetworkRequestWithIntent(msg);
2832 break;
2833 }
Erik Kline57faba92015-11-25 12:49:38 +09002834 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2835 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2836 handleTimedOutNetworkRequest(nri);
2837 break;
2838 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002839 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2840 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2841 break;
2842 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002843 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002844 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002845 break;
2846 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002847 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002848 Network network = (Network) msg.obj;
2849 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002850 break;
2851 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002852 case EVENT_SET_AVOID_UNVALIDATED: {
2853 handleSetAvoidUnvalidated((Network) msg.obj);
2854 break;
2855 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002856 case EVENT_PROMPT_UNVALIDATED: {
2857 handlePromptUnvalidated((Network) msg.obj);
2858 break;
2859 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002860 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2861 handleMobileDataAlwaysOn();
2862 break;
2863 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002864 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2865 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2866 mKeepaliveTracker.handleStartKeepalive(msg);
2867 break;
2868 }
2869 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2870 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2871 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2872 int slot = msg.arg1;
2873 int reason = msg.arg2;
2874 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2875 break;
2876 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002877 case EVENT_SYSTEM_READY: {
2878 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2879 nai.networkMonitor.systemReady = true;
2880 }
2881 break;
2882 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002883 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002884 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002885 break;
2886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
2888 }
2889 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002890
2891 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002893 public int tether(String iface, String callerPkg) {
2894 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002895 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002896 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002897 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002898 } else {
2899 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2900 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002901 }
2902
2903 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002904 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002905 public int untether(String iface, String callerPkg) {
2906 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002907
2908 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002909 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002910 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002911 } else {
2912 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2913 }
2914 }
2915
2916 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002917 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002918 public int getLastTetherError(String iface) {
2919 enforceTetherAccessPermission();
2920
2921 if (isTetheringSupported()) {
2922 return mTethering.getLastTetherError(iface);
2923 } else {
2924 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2925 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002926 }
2927
2928 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002929 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002930 public String[] getTetherableUsbRegexs() {
2931 enforceTetherAccessPermission();
2932 if (isTetheringSupported()) {
2933 return mTethering.getTetherableUsbRegexs();
2934 } else {
2935 return new String[0];
2936 }
2937 }
2938
Lorenzo Colitti18660282016-07-04 12:55:44 +09002939 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002940 public String[] getTetherableWifiRegexs() {
2941 enforceTetherAccessPermission();
2942 if (isTetheringSupported()) {
2943 return mTethering.getTetherableWifiRegexs();
2944 } else {
2945 return new String[0];
2946 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002947 }
2948
Lorenzo Colitti18660282016-07-04 12:55:44 +09002949 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002950 public String[] getTetherableBluetoothRegexs() {
2951 enforceTetherAccessPermission();
2952 if (isTetheringSupported()) {
2953 return mTethering.getTetherableBluetoothRegexs();
2954 } else {
2955 return new String[0];
2956 }
2957 }
2958
Lorenzo Colitti18660282016-07-04 12:55:44 +09002959 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002960 public int setUsbTethering(boolean enable, String callerPkg) {
2961 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002962 if (isTetheringSupported()) {
2963 return mTethering.setUsbTethering(enable);
2964 } else {
2965 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2966 }
2967 }
2968
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002969 // TODO - move iface listing, queries, etc to new module
2970 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002971 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002972 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002973 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974 return mTethering.getTetherableIfaces();
2975 }
2976
Lorenzo Colitti18660282016-07-04 12:55:44 +09002977 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002978 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002979 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002980 return mTethering.getTetheredIfaces();
2981 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002982
Lorenzo Colitti18660282016-07-04 12:55:44 +09002983 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002984 public String[] getTetheringErroredIfaces() {
2985 enforceTetherAccessPermission();
2986 return mTethering.getErroredIfaces();
2987 }
2988
Lorenzo Colitti18660282016-07-04 12:55:44 +09002989 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002990 public String[] getTetheredDhcpRanges() {
2991 enforceConnectivityInternalPermission();
2992 return mTethering.getTetheredDhcpRanges();
2993 }
2994
Udam Sainic3b640c2017-06-07 12:06:28 -07002995 @Override
2996 public boolean isTetheringSupported(String callerPkg) {
2997 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
2998 return isTetheringSupported();
2999 }
3000
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003001 // if ro.tether.denied = true we default to no tethering
3002 // gservices could set the secure setting to 1 though to enable it on a build where it
3003 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003004 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003005 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3006 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3007 Settings.Global.TETHER_SUPPORTED, defaultVal));
3008 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003009 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003010
3011 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3012 boolean adminUser = false;
3013 final long token = Binder.clearCallingIdentity();
3014 try {
3015 adminUser = mUserManager.isAdminUser();
3016 } finally {
3017 Binder.restoreCallingIdentity(token);
3018 }
3019
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003020 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003021 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003022
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003023 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003024 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3025 String callerPkg) {
3026 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003027 if (!isTetheringSupported()) {
3028 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3029 return;
3030 }
3031 mTethering.startTethering(type, receiver, showProvisioningUi);
3032 }
3033
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003034 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003035 public void stopTethering(int type, String callerPkg) {
3036 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003037 mTethering.stopTethering(type);
3038 }
3039
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003040 // Called when we lose the default network and have no replacement yet.
3041 // This will automatically be cleared after X seconds or a new default network
3042 // becomes CONNECTED, whichever happens first. The timer is started by the
3043 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003044 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003045 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003046 if (mNetTransitionWakeLock.isHeld()) {
3047 return;
3048 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003049 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003050 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3051 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003052 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003053 mWakelockLogs.log("ACQUIRE for " + forWhom);
3054 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3055 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003056 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003057
Hugo Benichi4c31b342017-03-30 23:18:10 +09003058 // Called when we gain a new default network to release the network transition wakelock in a
3059 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3060 // message is cancelled.
3061 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003062 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003063 if (!mNetTransitionWakeLock.isHeld()) {
3064 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003065 }
3066 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003067 // Cancel self timeout on wakelock hold.
3068 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3069 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3070 mHandler.sendMessageDelayed(msg, 1000);
3071 }
3072
3073 // Called when either message of ensureNetworkTransitionWakelock or
3074 // scheduleReleaseNetworkTransitionWakelock is processed.
3075 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3076 String event = eventName(eventId);
3077 synchronized (this) {
3078 if (!mNetTransitionWakeLock.isHeld()) {
3079 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3080 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3081 return;
3082 }
3083 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003084 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3085 mTotalWakelockDurationMs += lockDuration;
3086 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3087 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003088 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003089 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003090 }
3091
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003092 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003093 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003094 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003095 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003096 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003097 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003098 }
3099
Lorenzo Colitti18660282016-07-04 12:55:44 +09003100 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003101 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003102 enforceAccessPermission();
3103 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003104 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003105 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003106 mHandler.sendMessage(
3107 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3108 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003109
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003110 private void handleReportNetworkConnectivity(
3111 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003112 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003113 if (network == null) {
3114 nai = getDefaultNetwork();
3115 } else {
3116 nai = getNetworkAgentInfoForNetwork(network);
3117 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003118 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3119 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3120 return;
3121 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003122 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003123 if (hasConnectivity == nai.lastValidated) {
3124 return;
3125 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003126 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003127 int netid = nai.network.netId;
3128 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003129 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003130 // Validating a network that has not yet connected could result in a call to
3131 // rematchNetworkAndRequests() which is not meant to work on such networks.
3132 if (!nai.everConnected) {
3133 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003134 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003135 LinkProperties lp = getLinkProperties(nai);
3136 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3137 return;
3138 }
3139 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003140 }
3141
Paul Jensencee9b512015-05-06 07:32:40 -04003142 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003143 // this information is already available as a world read/writable jvm property
3144 // so this API change wouldn't have a benifit. It also breaks the passing
3145 // of proxy info to all the JVMs.
3146 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003147 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003148 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003149 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3150 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003151 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003152 }
3153
Lorenzo Colitti18660282016-07-04 12:55:44 +09003154 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003155 public ProxyInfo getProxyForNetwork(Network network) {
3156 if (network == null) return getDefaultProxy();
3157 final ProxyInfo globalProxy = getGlobalProxy();
3158 if (globalProxy != null) return globalProxy;
3159 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3160 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3161 // caller may not have.
3162 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3163 if (nai == null) return null;
3164 synchronized (nai) {
3165 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3166 if (proxyInfo == null) return null;
3167 return new ProxyInfo(proxyInfo);
3168 }
3169 }
3170
Paul Jensene0bef712014-12-10 15:12:18 -05003171 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3172 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3173 // proxy is null then there is no proxy in place).
3174 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3175 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3176 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3177 proxy = null;
3178 }
3179 return proxy;
3180 }
3181
3182 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3183 // better for determining if a new proxy broadcast is necessary:
3184 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3185 // avoid unnecessary broadcasts.
3186 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3187 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3188 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3189 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3190 // all set.
3191 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3192 a = canonicalizeProxyInfo(a);
3193 b = canonicalizeProxyInfo(b);
3194 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3195 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3196 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3197 }
3198
Jason Monk207900c2014-04-25 15:00:09 -04003199 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003200 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003201
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003202 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203 if (proxyProperties == mGlobalProxy) return;
3204 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3205 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3206
3207 String host = "";
3208 int port = 0;
3209 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003210 String pacFileUrl = "";
3211 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003212 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003213 if (!proxyProperties.isValid()) {
3214 if (DBG)
3215 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3216 return;
3217 }
Jason Monk207900c2014-04-25 15:00:09 -04003218 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003219 host = mGlobalProxy.getHost();
3220 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003221 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003222 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003223 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003224 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003225 } else {
3226 mGlobalProxy = null;
3227 }
3228 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003229 final long token = Binder.clearCallingIdentity();
3230 try {
3231 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3232 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3233 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3234 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003235 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003236 } finally {
3237 Binder.restoreCallingIdentity(token);
3238 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003239
Jason Monkcf0f97a2014-10-02 15:39:38 -04003240 if (mGlobalProxy == null) {
3241 proxyProperties = mDefaultProxy;
3242 }
3243 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003244 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003245 }
3246
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003247 private void loadGlobalProxy() {
3248 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003249 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3250 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3251 String exclList = Settings.Global.getString(res,
3252 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003253 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3254 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003255 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003256 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003257 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003258 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003259 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003260 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003261 if (!proxyProperties.isValid()) {
3262 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3263 return;
3264 }
3265
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003266 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003267 mGlobalProxy = proxyProperties;
3268 }
3269 }
3270 }
3271
Jason Monk207900c2014-04-25 15:00:09 -04003272 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003273 // this information is already available as a world read/writable jvm property
3274 // so this API change wouldn't have a benifit. It also breaks the passing
3275 // of proxy info to all the JVMs.
3276 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003277 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 return mGlobalProxy;
3279 }
3280 }
3281
Jason Monk207900c2014-04-25 15:00:09 -04003282 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003283 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003284 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003285 proxy = null;
3286 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003287 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003290 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003291 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3292 return;
3293 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003294
3295 // This call could be coming from the PacManager, containing the port of the local
3296 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3297 // global (to get the correct local port), and send a broadcast.
3298 // TODO: Switch PacManager to have its own message to send back rather than
3299 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003300 if ((mGlobalProxy != null) && (proxy != null)
3301 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003302 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3303 mGlobalProxy = proxy;
3304 sendProxyBroadcast(mGlobalProxy);
3305 return;
3306 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003307 mDefaultProxy = proxy;
3308
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003309 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003310 if (!mDefaultProxyDisabled) {
3311 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003312 }
3313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 }
3315
Paul Jensene0bef712014-12-10 15:12:18 -05003316 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3317 // This method gets called when any network changes proxy, but the broadcast only ever contains
3318 // the default proxy (even if it hasn't changed).
3319 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3320 // world where an app might be bound to a non-default network.
3321 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3322 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3323 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3324
3325 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3326 sendProxyBroadcast(getDefaultProxy());
3327 }
3328 }
3329
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003331 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3332 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003333 if (!TextUtils.isEmpty(proxy)) {
3334 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003335 if (data.length == 0) {
3336 return;
3337 }
3338
Robert Greenwalt434203a2010-10-11 16:00:27 -07003339 String proxyHost = data[0];
3340 int proxyPort = 8080;
3341 if (data.length > 1) {
3342 try {
3343 proxyPort = Integer.parseInt(data[1]);
3344 } catch (NumberFormatException e) {
3345 return;
3346 }
3347 }
Jason Monk207900c2014-04-25 15:00:09 -04003348 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 setGlobalProxy(p);
3350 }
3351 }
3352
Jason Monk207900c2014-04-25 15:00:09 -04003353 private void sendProxyBroadcast(ProxyInfo proxy) {
3354 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003355 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003356 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003358 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3359 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003360 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003361 final long ident = Binder.clearCallingIdentity();
3362 try {
3363 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3364 } finally {
3365 Binder.restoreCallingIdentity(ident);
3366 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003367 }
3368
3369 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003370 final private HashMap<Uri, Integer> mUriEventMap;
3371 final private Context mContext;
3372 final private Handler mHandler;
3373
3374 SettingsObserver(Context context, Handler handler) {
3375 super(null);
3376 mUriEventMap = new HashMap<Uri, Integer>();
3377 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003379 }
3380
Erik Klineda4bfa82015-04-30 12:58:40 +09003381 void observe(Uri uri, int what) {
3382 mUriEventMap.put(uri, what);
3383 final ContentResolver resolver = mContext.getContentResolver();
3384 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 }
3386
3387 @Override
3388 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003389 Slog.wtf(TAG, "Should never be reached.");
3390 }
3391
3392 @Override
3393 public void onChange(boolean selfChange, Uri uri) {
3394 final Integer what = mUriEventMap.get(uri);
3395 if (what != null) {
3396 mHandler.obtainMessage(what.intValue()).sendToTarget();
3397 } else {
3398 loge("No matching event to send for URI=" + uri);
3399 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003400 }
3401 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003402
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003403 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003404 Slog.d(TAG, s);
3405 }
3406
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003407 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003408 Slog.e(TAG, s);
3409 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003410
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003411 private static void loge(String s, Throwable t) {
3412 Slog.e(TAG, s, t);
3413 }
3414
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003415 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003416 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003417 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3418 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3419 *
3420 * @param oldPackage Package name of the application which currently controls VPN, which will
3421 * be replaced. If there is no such application, this should should either be
3422 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3423 * @param newPackage Package name of the application which should gain control of VPN, or
3424 * {@code null} to disable.
3425 * @param userId User for whom to prepare the new VPN.
3426 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003427 * @hide
3428 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003429 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003430 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3431 int userId) {
3432 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003433
Hugo Benichi20035e02017-04-26 14:53:28 +09003434 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003435 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003436 Vpn vpn = mVpns.get(userId);
3437 if (vpn != null) {
3438 return vpn.prepare(oldPackage, newPackage);
3439 } else {
3440 return false;
3441 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003443 }
3444
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003445 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003446 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3447 * This method is used by system-privileged apps.
3448 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3449 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3450 *
3451 * @param packageName The package for which authorization state should change.
3452 * @param userId User for whom {@code packageName} is installed.
3453 * @param authorized {@code true} if this app should be able to start a VPN connection without
3454 * explicit user approval, {@code false} if not.
3455 *
Jeff Davidson05542602014-08-11 14:07:27 -07003456 * @hide
3457 */
3458 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003459 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3460 enforceCrossUserPermission(userId);
3461
Hugo Benichi20035e02017-04-26 14:53:28 +09003462 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003463 Vpn vpn = mVpns.get(userId);
3464 if (vpn != null) {
3465 vpn.setPackageAuthorization(packageName, authorized);
3466 }
Jeff Davidson05542602014-08-11 14:07:27 -07003467 }
3468 }
3469
3470 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003471 * Configure a TUN interface and return its file descriptor. Parameters
3472 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003473 * and not available in ConnectivityManager. Permissions are checked in
3474 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003475 * @hide
3476 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003477 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003478 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003479 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003480 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003481 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003482 return mVpns.get(user).establish(config);
3483 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003484 }
3485
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003486 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003487 * Start legacy VPN, controlling native daemons as needed. Creates a
3488 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003489 */
3490 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003491 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003492 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003493 final LinkProperties egress = getActiveLinkProperties();
3494 if (egress == null) {
3495 throw new IllegalStateException("Missing active network connection");
3496 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003497 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003498 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003499 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3500 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003501 }
3502
3503 /**
3504 * Return the information of the ongoing legacy VPN. This method is used
3505 * by VpnSettings and not available in ConnectivityManager. Permissions
3506 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003507 */
3508 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003509 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3510 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003511
Hugo Benichi20035e02017-04-26 14:53:28 +09003512 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003513 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003514 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003515 }
3516
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003517 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003518 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3519 * and not available in ConnectivityManager.
3520 */
3521 @Override
3522 public VpnInfo[] getAllVpnInfo() {
3523 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003524 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003525 if (mLockdownEnabled) {
3526 return new VpnInfo[0];
3527 }
3528
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003529 List<VpnInfo> infoList = new ArrayList<>();
3530 for (int i = 0; i < mVpns.size(); i++) {
3531 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3532 if (info != null) {
3533 infoList.add(info);
3534 }
3535 }
3536 return infoList.toArray(new VpnInfo[infoList.size()]);
3537 }
3538 }
3539
3540 /**
3541 * @return VPN information for accounting, or null if we can't retrieve all required
3542 * information, e.g primary underlying iface.
3543 */
3544 @Nullable
3545 private VpnInfo createVpnInfo(Vpn vpn) {
3546 VpnInfo info = vpn.getVpnInfo();
3547 if (info == null) {
3548 return null;
3549 }
3550 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3551 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3552 // the underlyingNetworks list.
3553 if (underlyingNetworks == null) {
3554 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3555 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3556 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3557 }
3558 } else if (underlyingNetworks.length > 0) {
3559 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3560 if (linkProperties != null) {
3561 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3562 }
3563 }
3564 return info.primaryUnderlyingIface == null ? null : info;
3565 }
3566
3567 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003568 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3569 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003570 * Permissions are checked in Vpn class.
3571 * @hide
3572 */
3573 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003574 public VpnConfig getVpnConfig(int userId) {
3575 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003576 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003577 Vpn vpn = mVpns.get(userId);
3578 if (vpn != null) {
3579 return vpn.getVpnConfig();
3580 } else {
3581 return null;
3582 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003583 }
3584 }
3585
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003586 @Override
3587 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003588 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3589 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3590 return false;
3591 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003592
Hugo Benichi69744342017-11-27 10:57:16 +09003593 synchronized (mVpns) {
3594 // Tear down existing lockdown if profile was removed
3595 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3596 if (mLockdownEnabled) {
3597 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3598 if (profileTag == null) {
3599 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3600 return false;
3601 }
3602 String profileName = new String(profileTag);
3603 final VpnProfile profile = VpnProfile.decode(
3604 profileName, mKeyStore.get(Credentials.VPN + profileName));
3605 if (profile == null) {
3606 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3607 setLockdownTracker(null);
3608 return true;
3609 }
3610 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003611 Vpn vpn = mVpns.get(user);
3612 if (vpn == null) {
3613 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3614 return false;
3615 }
3616 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003617 } else {
3618 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003620 }
3621
3622 return true;
3623 }
3624
3625 /**
3626 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3627 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3628 */
Hugo Benichi69744342017-11-27 10:57:16 +09003629 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003630 private void setLockdownTracker(LockdownVpnTracker tracker) {
3631 // Shutdown any existing tracker
3632 final LockdownVpnTracker existing = mLockdownTracker;
3633 mLockdownTracker = null;
3634 if (existing != null) {
3635 existing.shutdown();
3636 }
3637
Robin Leec3736bc2017-03-10 16:19:54 +00003638 if (tracker != null) {
3639 mLockdownTracker = tracker;
3640 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003641 }
3642 }
3643
Hugo Benichi69744342017-11-27 10:57:16 +09003644 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003645 private void throwIfLockdownEnabled() {
3646 if (mLockdownEnabled) {
3647 throw new IllegalStateException("Unavailable in lockdown mode");
3648 }
3649 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003650
Robin Lee244ce8e2016-01-05 18:03:46 +00003651 /**
Robin Lee17e61832016-05-09 13:46:28 +01003652 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3653 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003654 *
Robin Lee17e61832016-05-09 13:46:28 +01003655 * @return {@code true} if the service was started, the service was already connected, or there
3656 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003657 */
Robin Lee17e61832016-05-09 13:46:28 +01003658 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003659 synchronized (mVpns) {
3660 Vpn vpn = mVpns.get(userId);
3661 if (vpn == null) {
3662 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3663 // exists already.
3664 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3665 return false;
3666 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003667
Robin Lee812800c2016-05-13 15:38:08 +01003668 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003669 }
3670 }
3671
3672 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003673 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3674 enforceSettingsPermission();
3675 enforceCrossUserPermission(userId);
3676
3677 synchronized (mVpns) {
3678 Vpn vpn = mVpns.get(userId);
3679 if (vpn == null) {
3680 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3681 return false;
3682 }
3683 return vpn.isAlwaysOnPackageSupported(packageName);
3684 }
3685 }
3686
3687 @Override
Robin Leedc679712016-05-03 13:23:03 +01003688 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003689 enforceConnectivityInternalPermission();
3690 enforceCrossUserPermission(userId);
3691
Robin Lee244ce8e2016-01-05 18:03:46 +00003692 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003693 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3694 if (LockdownVpnTracker.isEnabled()) {
3695 return false;
3696 }
3697
Robin Lee244ce8e2016-01-05 18:03:46 +00003698 Vpn vpn = mVpns.get(userId);
3699 if (vpn == null) {
3700 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3701 return false;
3702 }
Robin Lee17e61832016-05-09 13:46:28 +01003703 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003704 return false;
3705 }
Robin Lee17e61832016-05-09 13:46:28 +01003706 if (!startAlwaysOnVpn(userId)) {
3707 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003708 return false;
3709 }
3710 }
3711 return true;
3712 }
3713
3714 @Override
3715 public String getAlwaysOnVpnPackage(int userId) {
3716 enforceConnectivityInternalPermission();
3717 enforceCrossUserPermission(userId);
3718
3719 synchronized (mVpns) {
3720 Vpn vpn = mVpns.get(userId);
3721 if (vpn == null) {
3722 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3723 return null;
3724 }
3725 return vpn.getAlwaysOnPackage();
3726 }
3727 }
3728
Wink Savilleab9321d2013-06-29 21:10:57 -07003729 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003730 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003731 // TODO: Remove? Any reason to trigger a provisioning check?
3732 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003733 }
3734
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003735 /** Location to an updatable file listing carrier provisioning urls.
3736 * An example:
3737 *
3738 * <?xml version="1.0" encoding="utf-8"?>
3739 * <provisioningUrls>
3740 * <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 -07003741 * </provisioningUrls>
3742 */
3743 private static final String PROVISIONING_URL_PATH =
3744 "/data/misc/radio/provisioning_urls.xml";
3745 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003746
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003747 /** XML tag for root element. */
3748 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3749 /** XML tag for individual url */
3750 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003751 /** XML attribute for mcc */
3752 private static final String ATTR_MCC = "mcc";
3753 /** XML attribute for mnc */
3754 private static final String ATTR_MNC = "mnc";
3755
Paul Jensen434dde82015-06-11 09:43:30 -04003756 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003757 FileReader fileReader = null;
3758 XmlPullParser parser = null;
3759 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003760
3761 try {
3762 fileReader = new FileReader(mProvisioningUrlFile);
3763 parser = Xml.newPullParser();
3764 parser.setInput(fileReader);
3765 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3766
3767 while (true) {
3768 XmlUtils.nextElement(parser);
3769
3770 String element = parser.getName();
3771 if (element == null) break;
3772
Paul Jensen434dde82015-06-11 09:43:30 -04003773 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003774 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3775 try {
3776 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3777 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3778 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3779 parser.next();
3780 if (parser.getEventType() == XmlPullParser.TEXT) {
3781 return parser.getText();
3782 }
3783 }
3784 }
3785 } catch (NumberFormatException e) {
3786 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3787 }
3788 }
3789 }
3790 return null;
3791 } catch (FileNotFoundException e) {
3792 loge("Carrier Provisioning Urls file not found");
3793 } catch (XmlPullParserException e) {
3794 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3795 } catch (IOException e) {
3796 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3797 } finally {
3798 if (fileReader != null) {
3799 try {
3800 fileReader.close();
3801 } catch (IOException e) {}
3802 }
3803 }
3804 return null;
3805 }
3806
Wink Saville42d4f082013-07-20 20:31:59 -07003807 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003808 public String getMobileProvisioningUrl() {
3809 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003810 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811 if (TextUtils.isEmpty(url)) {
3812 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003813 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003814 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003815 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003816 }
Wink Saville8cf35602013-07-10 23:00:07 -07003817 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003818 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003819 String phoneNumber = mTelephonyManager.getLine1Number();
3820 if (TextUtils.isEmpty(phoneNumber)) {
3821 phoneNumber = "0000000000";
3822 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003823 url = String.format(url,
3824 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3825 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003826 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003827 }
3828
Wink Savilleab9321d2013-06-29 21:10:57 -07003829 return url;
3830 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003831
Wink Saville948282b2013-08-29 08:55:16 -07003832 @Override
3833 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003834 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003835 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003836 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3837 return;
3838 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003839 final long ident = Binder.clearCallingIdentity();
3840 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003841 // Concatenate the range of types onto the range of NetIDs.
3842 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3843 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003844 } finally {
3845 Binder.restoreCallingIdentity(ident);
3846 }
Wink Saville948282b2013-08-29 08:55:16 -07003847 }
Wink Saville7788c612013-08-29 14:57:08 -07003848
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003849 @Override
3850 public void setAirplaneMode(boolean enable) {
3851 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003852 final long ident = Binder.clearCallingIdentity();
3853 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003854 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003855 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003856 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3857 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003858 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003859 } finally {
3860 Binder.restoreCallingIdentity(ident);
3861 }
3862 }
3863
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003864 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003865 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003866 Vpn userVpn = mVpns.get(userId);
3867 if (userVpn != null) {
3868 loge("Starting user already has a VPN");
3869 return;
3870 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003871 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003872 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003873 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3874 updateLockdownVpn();
3875 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003876 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 }
3878
3879 private void onUserStop(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) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003883 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003884 return;
3885 }
Robin Lee17e61832016-05-09 13:46:28 +01003886 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887 mVpns.delete(userId);
3888 }
3889 }
3890
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003891 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003892 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003893 final int vpnsSize = mVpns.size();
3894 for (int i = 0; i < vpnsSize; i++) {
3895 Vpn vpn = mVpns.valueAt(i);
3896 vpn.onUserAdded(userId);
3897 }
3898 }
3899 }
3900
3901 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003902 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003903 final int vpnsSize = mVpns.size();
3904 for (int i = 0; i < vpnsSize; i++) {
3905 Vpn vpn = mVpns.valueAt(i);
3906 vpn.onUserRemoved(userId);
3907 }
3908 }
3909 }
3910
Robin Lee89e7a692016-02-29 14:38:17 +00003911 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09003912 synchronized (mVpns) {
3913 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3914 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3915 updateLockdownVpn();
3916 } else {
3917 startAlwaysOnVpn(userId);
3918 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003919 }
3920 }
3921
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003922 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3923 @Override
3924 public void onReceive(Context context, Intent intent) {
3925 final String action = intent.getAction();
3926 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3927 if (userId == UserHandle.USER_NULL) return;
3928
Robin Lee323f29d2016-05-04 16:38:06 +01003929 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003930 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003931 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003932 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003933 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3934 onUserAdded(userId);
3935 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3936 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003937 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3938 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003939 }
3940 }
3941 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003942
Robin Lee95204e02017-01-27 11:59:22 +00003943 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3944 @Override
3945 public void onReceive(Context context, Intent intent) {
3946 // Try creating lockdown tracker, since user present usually means
3947 // unlocked keystore.
3948 updateLockdownVpn();
3949 mContext.unregisterReceiver(this);
3950 }
3951 };
3952
Robert Greenwalta67be032014-05-16 15:49:14 -07003953 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3954 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003955 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3956 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003957
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003958 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3959 // Map from UID to number of NetworkRequests that UID has filed.
3960 @GuardedBy("mUidToNetworkRequestCount")
3961 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3962
Robert Greenwalta67be032014-05-16 15:49:14 -07003963 private static class NetworkFactoryInfo {
3964 public final String name;
3965 public final Messenger messenger;
3966 public final AsyncChannel asyncChannel;
3967
3968 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3969 this.name = name;
3970 this.messenger = messenger;
3971 this.asyncChannel = asyncChannel;
3972 }
3973 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003974
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003975 private void ensureNetworkRequestHasType(NetworkRequest request) {
3976 if (request.type == NetworkRequest.Type.NONE) {
3977 throw new IllegalArgumentException(
3978 "All NetworkRequests in ConnectivityService must have a type");
3979 }
3980 }
3981
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003982 /**
3983 * Tracks info about the requester.
3984 * Also used to notice when the calling process dies so we can self-expire
3985 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003988 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003989 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003990 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991 final int mPid;
3992 final int mUid;
3993 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003995 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003996 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003997 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003998 mPendingIntent = pi;
3999 messenger = null;
4000 mBinder = null;
4001 mPid = getCallingPid();
4002 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004003 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004004 }
4005
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004006 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 super();
4008 messenger = m;
4009 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004010 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 mBinder = binder;
4012 mPid = getCallingPid();
4013 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004014 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004015 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016
4017 try {
4018 mBinder.linkToDeath(this, 0);
4019 } catch (RemoteException e) {
4020 binderDied();
4021 }
4022 }
4023
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004024 private void enforceRequestCountLimit() {
4025 synchronized (mUidToNetworkRequestCount) {
4026 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4027 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004028 throw new ServiceSpecificException(
4029 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004030 }
4031 mUidToNetworkRequestCount.put(mUid, networkRequests);
4032 }
4033 }
4034
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 if (mBinder != null) {
4037 mBinder.unlinkToDeath(this, 0);
4038 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 }
4040
4041 public void binderDied() {
4042 log("ConnectivityService NetworkRequestInfo binderDied(" +
4043 request + ", " + mBinder + ")");
4044 releaseNetworkRequest(request);
4045 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004046
4047 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004048 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004049 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004050 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004051 }
4052
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004053 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4054 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4055 if (badCapability != null) {
4056 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004057 }
4058 }
4059
Erik Kline9d598e12015-07-13 16:37:51 +09004060 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004061 final SortedSet<Integer> thresholds = new TreeSet();
4062 synchronized (nai) {
4063 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4064 if (nri.request.networkCapabilities.hasSignalStrength() &&
4065 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4066 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4067 }
4068 }
4069 }
Erik Kline9d598e12015-07-13 16:37:51 +09004070 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004071 }
4072
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004073 private void updateSignalStrengthThresholds(
4074 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4075 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004076 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004077 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4078
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004079 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004080 String detail;
4081 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4082 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4083 } else {
4084 detail = reason;
4085 }
4086 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4087 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4088 }
4089
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004090 nai.asyncChannel.sendMessage(
4091 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004092 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004093 }
4094
Etan Cohen859748f2017-04-03 17:42:34 -07004095 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4096 if (nc == null) {
4097 return;
4098 }
4099 NetworkSpecifier ns = nc.getNetworkSpecifier();
4100 if (ns == null) {
4101 return;
4102 }
4103 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4104 ns.assertValidFromUid(Binder.getCallingUid());
4105 }
4106
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 @Override
4108 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004109 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004110 final NetworkRequest.Type type = (networkCapabilities == null)
4111 ? NetworkRequest.Type.TRACK_DEFAULT
4112 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004113 // If the requested networkCapabilities is null, take them instead from
4114 // the default network request. This allows callers to keep track of
4115 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004116 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004117 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4118 enforceAccessPermission();
4119 } else {
4120 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4121 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004122 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4123 // of the app when the request is filed, but we never change the request if the app
4124 // changes network state. http://b/29964605
4125 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004126 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004127 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004128
Etan Cohenba07c8c2017-02-05 10:42:27 -08004129 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004130 throw new IllegalArgumentException("Bad timeout specified");
4131 }
Etan Cohen859748f2017-04-03 17:42:34 -07004132 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004133
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004134 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004135 nextNetworkRequestId(), type);
4136 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004137 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004138
4139 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004140 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004142 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 }
4144 return networkRequest;
4145 }
4146
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004147 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004148 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004149 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004150 } else {
4151 enforceChangePermission();
4152 }
4153 }
4154
fenglub15e72b2015-03-20 11:29:56 -07004155 @Override
fengludb571472015-04-21 17:12:05 -07004156 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004157 enforceAccessPermission();
4158 NetworkAgentInfo nai = null;
4159 if (network == null) {
4160 return false;
4161 }
4162 synchronized (mNetworkForNetId) {
4163 nai = mNetworkForNetId.get(network.netId);
4164 }
4165 if (nai != null) {
4166 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4167 return true;
4168 }
4169 return false;
4170 }
4171
Felipe Lemeee27cab2016-06-20 16:36:29 -07004172 private boolean isSystem(int uid) {
4173 return uid < Process.FIRST_APPLICATION_UID;
4174 }
fenglub15e72b2015-03-20 11:29:56 -07004175
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004176 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004177 final int uid = Binder.getCallingUid();
4178 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004179 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004180 return;
4181 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004182 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4183 // Policy already enforced.
4184 return;
4185 }
4186 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4187 // If UID is restricted, don't allow them to bring up metered APNs.
4188 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 }
4190 }
4191
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 @Override
4193 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4194 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004195 checkNotNull(operation, "PendingIntent cannot be null.");
4196 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4197 enforceNetworkRequestPermissions(networkCapabilities);
4198 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004199 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004200 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004201
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004202 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004203 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4204 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004205 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4207 nri));
4208 return networkRequest;
4209 }
4210
Jeremy Joslin79294842014-12-03 17:15:28 -08004211 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4212 mHandler.sendMessageDelayed(
4213 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4214 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4215 }
4216
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 @Override
4218 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004219 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4221 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004222 }
4223
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004224 // In order to implement the compatibility measure for pre-M apps that call
4225 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4226 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4227 // This ensures it has permission to do so.
4228 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4229 if (nc == null) {
4230 return false;
4231 }
4232 int[] transportTypes = nc.getTransportTypes();
4233 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4234 return false;
4235 }
4236 try {
4237 mContext.enforceCallingOrSelfPermission(
4238 android.Manifest.permission.ACCESS_WIFI_STATE,
4239 "ConnectivityService");
4240 } catch (SecurityException e) {
4241 return false;
4242 }
4243 return true;
4244 }
4245
Robert Greenwalt9258c642014-03-26 16:47:06 -07004246 @Override
4247 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4248 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004249 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4250 enforceAccessPermission();
4251 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004252
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004253 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4254 if (!ConnectivityManager.checkChangePermission(mContext)) {
4255 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4256 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4257 // onLost and onAvailable callbacks when networks move in and out of the background.
4258 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4259 // can't request networks.
4260 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4261 }
Etan Cohen859748f2017-04-03 17:42:34 -07004262 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004263
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004264 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004265 NetworkRequest.Type.LISTEN);
4266 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004267 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004268
4269 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4270 return networkRequest;
4271 }
4272
4273 @Override
4274 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4275 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004276 checkNotNull(operation, "PendingIntent cannot be null.");
4277 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4278 enforceAccessPermission();
4279 }
Etan Cohen859748f2017-04-03 17:42:34 -07004280 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004281
Erik Kline7523eb32015-07-09 18:24:03 +09004282 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004283 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4284 NetworkRequest.Type.LISTEN);
4285 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004286 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004287
4288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004289 }
4290
Erik Klineacdd6392016-07-07 16:50:58 +09004291 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004292 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004293 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004294 mHandler.sendMessage(mHandler.obtainMessage(
4295 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004296 }
4297
4298 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004299 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004300 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004301 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4302 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004303 }
4304
Robert Greenwalta67be032014-05-16 15:49:14 -07004305 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004306 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004307 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4308 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4309 }
4310
4311 @Override
4312 public void unregisterNetworkFactory(Messenger messenger) {
4313 enforceConnectivityInternalPermission();
4314 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4315 }
4316
4317 private void handleUnregisterNetworkFactory(Messenger messenger) {
4318 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4319 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004320 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004321 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004323 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004324 }
4325
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 /**
4327 * NetworkAgentInfo supporting a request by requestId.
4328 * These have already been vetted (their Capabilities satisfy the request)
4329 * and the are the highest scored network available.
4330 * the are keyed off the Requests requestId.
4331 */
Hugo Benichicd952782017-09-20 11:20:14 +09004332 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4333 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4335 new SparseArray<NetworkAgentInfo>();
4336
Paul Jensen31a94f42015-02-13 14:18:39 -05004337 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4338 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004339 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4340 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004341 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4342 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4343 // there may not be a strict 1:1 correlation between the two.
4344 @GuardedBy("mNetworkForNetId")
4345 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346
Robert Greenwalt7b816022014-04-18 15:25:25 -07004347 // NetworkAgentInfo keyed off its connecting messenger
4348 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004349 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4351 new HashMap<Messenger, NetworkAgentInfo>();
4352
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004353 @GuardedBy("mBlockedAppUids")
4354 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4355
Paul Jensen2c311d62014-11-17 12:34:51 -05004356 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004357 private final NetworkRequest mDefaultRequest;
4358
Erik Klineda4bfa82015-04-30 12:58:40 +09004359 // Request used to optionally keep mobile data active even when higher
4360 // priority networks like Wi-Fi are active.
4361 private final NetworkRequest mDefaultMobileDataRequest;
4362
Hugo Benichicd952782017-09-20 11:20:14 +09004363 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4364 synchronized (mNetworkForRequestId) {
4365 return mNetworkForRequestId.get(requestId);
4366 }
4367 }
4368
4369 private void clearNetworkForRequest(int requestId) {
4370 synchronized (mNetworkForRequestId) {
4371 mNetworkForRequestId.remove(requestId);
4372 }
4373 }
4374
4375 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4376 synchronized (mNetworkForRequestId) {
4377 mNetworkForRequestId.put(requestId, nai);
4378 }
4379 }
4380
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004381 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004382 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004383 }
4384
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004385 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004386 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004387 }
4388
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004389 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4390 return nri.request.requestId == mDefaultRequest.requestId;
4391 }
4392
Paul Jensen31a94f42015-02-13 14:18:39 -05004393 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004395 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004396 enforceConnectivityInternalPermission();
4397
Rubin Xu1bb5c082017-09-05 18:40:49 +01004398 LinkProperties lp = new LinkProperties(linkProperties);
4399 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004400 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4401 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004402 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004403 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4404 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004405 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004406 synchronized (this) {
4407 nai.networkMonitor.systemReady = mSystemReady;
4408 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004409 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4410 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004411 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004413 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 }
4415
4416 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4417 if (VDBG) log("Got NetworkAgent Messenger");
4418 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004419 synchronized (mNetworkForNetId) {
4420 mNetworkForNetId.put(na.network.netId, na);
4421 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4423 NetworkInfo networkInfo = na.networkInfo;
4424 na.networkInfo = null;
4425 updateNetworkInfo(na, networkInfo);
4426 }
4427
4428 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4429 LinkProperties newLp = networkAgent.linkProperties;
4430 int netId = networkAgent.network.netId;
4431
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004432 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4433 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004434 if (networkAgent.clatd != null) {
4435 networkAgent.clatd.fixupLinkProperties(oldLp);
4436 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004437
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004438 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439 updateMtu(newLp, oldLp);
4440 // TODO - figure out what to do for clat
4441// for (LinkProperties lp : newLp.getStackedLinks()) {
4442// updateMtu(lp, null);
4443// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004444 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004445
Erik Kline94887872016-04-05 13:30:49 +09004446 updateRoutes(newLp, oldLp, netId);
4447 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004448
Hugo Benichib577d652017-06-27 15:13:20 +09004449 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004450 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004451 if (isDefaultNetwork(networkAgent)) {
4452 handleApplyDefaultProxy(newLp.getHttpProxy());
4453 } else {
4454 updateProxy(newLp, oldLp, networkAgent);
4455 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004456 // TODO - move this check to cover the whole function
4457 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004458 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004459 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4460 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004461
4462 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004463 }
4464
Joel Scherpelz668370b2017-06-08 15:35:21 +09004465 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004466 // Marks are only available on WiFi interaces. Checking for
4467 // marks on unsupported interfaces is harmless.
4468 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4469 return;
4470 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004471
Joel Scherpelz668370b2017-06-08 15:35:21 +09004472 int mark = mContext.getResources().getInteger(
4473 com.android.internal.R.integer.config_networkWakeupPacketMark);
4474 int mask = mContext.getResources().getInteger(
4475 com.android.internal.R.integer.config_networkWakeupPacketMask);
4476
4477 // Mask/mark of zero will not detect anything interesting.
4478 // Don't install rules unless both values are nonzero.
4479 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004480 return;
4481 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004482
4483 final String prefix = "iface:" + iface;
4484 try {
4485 if (add) {
4486 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4487 } else {
4488 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4489 }
4490 } catch (Exception e) {
4491 loge("Exception modifying wakeup packet monitoring: " + e);
4492 }
4493
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004494 }
4495
4496 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4497 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004498 CompareResult<String> interfaceDiff = new CompareResult<String>(
4499 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4500 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004501 for (String iface : interfaceDiff.added) {
4502 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004503 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004504 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004505 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004506 } catch (Exception e) {
4507 loge("Exception adding interface: " + e);
4508 }
4509 }
4510 for (String iface : interfaceDiff.removed) {
4511 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004512 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004513 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004514 mNetd.removeInterfaceFromNetwork(iface, netId);
4515 } catch (Exception e) {
4516 loge("Exception removing interface: " + e);
4517 }
4518 }
4519 }
4520
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004521 /**
4522 * Have netd update routes from oldLp to newLp.
4523 * @return true if routes changed between oldLp and newLp
4524 */
4525 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004526 // Compare the route diff to determine which routes should be added and removed.
4527 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4528 oldLp != null ? oldLp.getAllRoutes() : null,
4529 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530
4531 // add routes before removing old in case it helps with continuous connectivity
4532
4533 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4534 for (RouteInfo route : routeDiff.added) {
4535 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004536 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 try {
4538 mNetd.addRoute(netId, route);
4539 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004540 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4541 loge("Exception in addRoute for non-gateway: " + e);
4542 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 }
4544 }
4545 for (RouteInfo route : routeDiff.added) {
4546 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004547 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004548 try {
4549 mNetd.addRoute(netId, route);
4550 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004551 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4552 loge("Exception in addRoute for gateway: " + e);
4553 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
4555 }
4556
4557 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004558 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 try {
4560 mNetd.removeRoute(netId, route);
4561 } catch (Exception e) {
4562 loge("Exception in removeRoute: " + e);
4563 }
4564 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004565 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004566 }
Erik Kline41368502015-06-17 13:19:54 +09004567
Erik Kline94887872016-04-05 13:30:49 +09004568 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4569 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4570 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004571 }
Erik Kline94887872016-04-05 13:30:49 +09004572
4573 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004574 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004575 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004576 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004577 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4578 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004579 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004580 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004581 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4582 if (defaultNai != null && defaultNai.network.netId == netId) {
4583 setDefaultDnsSystemProperties(dnses);
4584 }
Erik Kline94887872016-04-05 13:30:49 +09004585 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
4587
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004588 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4589 int last = 0;
4590 for (InetAddress dns : dnses) {
4591 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004592 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004593 }
4594 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004595 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004596 }
4597 mNumDnsEntries = last;
4598 }
4599
Erik Kline4edba012017-04-07 15:29:29 +09004600 private void setNetDnsProperty(int which, String value) {
4601 final String key = "net.dns" + which;
4602 // Log and forget errors setting unsupported properties.
4603 try {
4604 mSystemProperties.set(key, value);
4605 } catch (Exception e) {
4606 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4607 }
4608 }
4609
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004610 private String getNetworkPermission(NetworkCapabilities nc) {
4611 // TODO: make these permission strings AIDL constants instead.
4612 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4613 return NetworkManagementService.PERMISSION_SYSTEM;
4614 }
4615 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4616 return NetworkManagementService.PERMISSION_NETWORK;
4617 }
4618 return null;
4619 }
4620
Paul Jensen3d194ea2015-06-16 14:27:36 -04004621 /**
4622 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4623 * augmented with any stateful capabilities implied from {@code networkAgent}
4624 * (e.g., validated status and captive portal status).
4625 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004626 * @param oldScore score of the network before any of the changes that prompted us
4627 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004628 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004629 * @param networkCapabilities the new network capabilities.
4630 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004631 private void updateCapabilities(
4632 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004633 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004634 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4635 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004636 // TODO: consider not complaining when a network agent degrade its capabilities if this
4637 // does not cause any request (that is not a listen) currently matching that agent to
4638 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004639 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4640 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004641 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004642 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004643 }
4644
Paul Jensen3d194ea2015-06-16 14:27:36 -04004645 // Don't modify caller's NetworkCapabilities.
4646 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004647 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004648 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4649 } else {
4650 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4651 }
Paul Jensene0988542015-06-25 15:30:08 -04004652 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004653 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4654 } else {
4655 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4656 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004657 if (nai.isBackgroundNetwork()) {
4658 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4659 } else {
4660 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4661 }
4662
4663 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4664
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004665 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4666 final String newPermission = getNetworkPermission(networkCapabilities);
4667 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004668 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004669 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004670 } catch (RemoteException e) {
4671 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004672 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004673 }
4674
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004675 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004676 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004677 prevNc = nai.networkCapabilities;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004678 nai.networkCapabilities = networkCapabilities;
4679 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004680
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004681 if (nai.getCurrentScore() == oldScore &&
4682 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4683 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4684 // the change we're processing can't affect any requests, it can only affect the listens
4685 // on this network. We might have been called by rematchNetworkAndRequests when a
4686 // network changed foreground state.
4687 processListenRequests(nai, true);
4688 } else {
4689 // If the requestable capabilities have changed or the score changed, we can't have been
4690 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004691 rematchAllNetworksAndRequests(nai, oldScore);
4692 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004693 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004694
4695 // Report changes that are interesting for network statistics tracking.
4696 if (prevNc != null) {
4697 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
4698 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED);
4699 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
4700 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING);
4701 if (meteredChanged || roamingChanged) {
4702 notifyIfacesChangedForNetworkStats();
4703 }
4704 }
4705
4706 if (!networkCapabilities.hasTransport(TRANSPORT_VPN)) {
4707 // Tell VPNs about updated capabilities, since they may need to
4708 // bubble those changes through.
4709 synchronized (mVpns) {
4710 for (int i = 0; i < mVpns.size(); i++) {
4711 final Vpn vpn = mVpns.valueAt(i);
4712 vpn.updateCapabilities();
4713 }
4714 }
4715 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004716 }
4717
Hugo Benichief502882017-09-01 01:23:32 +00004718 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4719 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4720 // Ignore updates for disconnected networks
4721 return;
4722 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004723 // newLp is already a defensive copy.
4724 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004725 if (VDBG) {
4726 log("Update of LinkProperties for " + nai.name() +
4727 "; created=" + nai.created +
4728 "; everConnected=" + nai.everConnected);
4729 }
4730 LinkProperties oldLp = nai.linkProperties;
4731 synchronized (nai) {
4732 nai.linkProperties = newLp;
4733 }
4734 if (nai.everConnected) {
4735 updateLinkProperties(nai, oldLp);
4736 }
4737 }
4738
Paul Jensenc8b9a742014-09-30 15:37:41 -04004739 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004740 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4741 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004742 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004743 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004744 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4745 }
4746 }
4747
Robert Greenwalt7b816022014-04-18 15:25:25 -07004748 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4749 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004750 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004751 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4752 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004753 }
4754 }
4755
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004756 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4757 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004758 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004759 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004760 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4761 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004762 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004763 sendIntent(nri.mPendingIntent, intent);
4764 }
4765 // else not handled
4766 }
4767
4768 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4769 mPendingIntentWakeLock.acquire();
4770 try {
4771 if (DBG) log("Sending " + pendingIntent);
4772 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4773 } catch (PendingIntent.CanceledException e) {
4774 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4775 mPendingIntentWakeLock.release();
4776 releasePendingNetworkRequest(pendingIntent);
4777 }
4778 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4779 }
4780
4781 @Override
4782 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4783 String resultData, Bundle resultExtras) {
4784 if (DBG) log("Finished sending " + pendingIntent);
4785 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004786 // Release with a delay so the receiving client has an opportunity to put in its
4787 // own request.
4788 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004789 }
4790
Hugo Benichidba33db2017-03-23 22:40:44 +09004791 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004792 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004793 if (nri.messenger == null) {
4794 return; // Default request has no msgr
4795 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004796 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004797 // TODO: check if defensive copies of data is needed.
4798 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004799 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004800 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4801 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004802 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004803 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004804 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004805 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004806 break;
4807 }
4808 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004809 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004810 break;
4811 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004812 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004813 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004814 break;
4815 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004816 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004817 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004818 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004819 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004820 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004821 String notification = ConnectivityManager.getCallbackName(notificationType);
4822 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004823 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004824 nri.messenger.send(msg);
4825 } catch (RemoteException e) {
4826 // may occur naturally in the race of binder death.
4827 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4828 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004829 }
4830
Hugo Benichidba33db2017-03-23 22:40:44 +09004831 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4832 bundle.putParcelable(t.getClass().getSimpleName(), t);
4833 }
4834
Paul Jensenc8b9a742014-09-30 15:37:41 -04004835 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004836 if (nai.numRequestNetworkRequests() != 0) {
4837 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4838 NetworkRequest nr = nai.requestAt(i);
4839 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004840 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004841 loge("Dead network still had at least " + nr);
4842 break;
4843 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004844 }
4845 nai.asyncChannel.disconnect();
4846 }
4847
Robert Greenwalt7b816022014-04-18 15:25:25 -07004848 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4849 if (oldNetwork == null) {
4850 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4851 return;
4852 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004853 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004854
4855 // If we get here it means that the last linger timeout for this network expired. So there
4856 // must be no other active linger timers, and we must stop lingering.
4857 oldNetwork.clearLingerState();
4858
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004859 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004860 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004861 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004862 } else {
4863 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004864 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4865 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004866 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004867 }
4868
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004869 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004870 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004871 setupDataActivityTracking(newNetwork);
4872 try {
4873 mNetd.setDefaultNetId(newNetwork.network.netId);
4874 } catch (Exception e) {
4875 loge("Exception setting default network :" + e);
4876 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004877 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004878 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004879 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004880 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004881 }
4882
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004884 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4885 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4886 NetworkRequest nr = nri.request;
4887 if (!nr.isListen()) continue;
4888 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4889 nai.removeRequest(nri.request.requestId);
4890 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4891 }
4892 }
4893
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004894 if (capabilitiesChanged) {
4895 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4896 }
4897
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004898 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4899 NetworkRequest nr = nri.request;
4900 if (!nr.isListen()) continue;
4901 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4902 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004903 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004904 }
4905 }
4906 }
4907
Paul Jensen2161a8e2014-09-11 11:00:39 -04004908 // Handles a network appearing or improving its score.
4909 //
4910 // - Evaluates all current NetworkRequests that can be
4911 // satisfied by newNetwork, and reassigns to newNetwork
4912 // any such requests for which newNetwork is the best.
4913 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004914 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004915 // needed. A network is needed if it is the best network for
4916 // one or more NetworkRequests, or if it is a VPN.
4917 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004918 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004919 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004920 //
4921 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4922 // networks that have no chance (i.e. even if validated)
4923 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004924 //
4925 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4926 // it does not remove NetworkRequests that other Networks could better satisfy.
4927 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4928 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4929 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004930 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004931 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004932 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4933 // performed to tear down unvalidated networks that have no chance (i.e. even if
4934 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004935 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004936 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004937 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004938 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004939 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004940 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004941
4942 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4943 final int score = newNetwork.getCurrentScore();
4944
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004945 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004946
Paul Jensen2161a8e2014-09-11 11:00:39 -04004947 // Find and migrate to this Network any NetworkRequests for
4948 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004949 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004950 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004951 NetworkCapabilities nc = newNetwork.networkCapabilities;
4952 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004953 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004954 // Process requests in the first pass and listens in the second pass. This allows us to
4955 // change a network's capabilities depending on which requests it has. This is only
4956 // correct if the change in capabilities doesn't affect whether the network satisfies
4957 // requests or not, and doesn't affect the network's score.
4958 if (nri.request.isListen()) continue;
4959
Hugo Benichicd952782017-09-20 11:20:14 +09004960 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004961 final boolean satisfies = newNetwork.satisfies(nri.request);
4962 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004963 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004964 log("Network " + newNetwork.name() + " was already satisfying" +
4965 " request " + nri.request.requestId + ". No change.");
4966 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004967 keep = true;
4968 continue;
4969 }
4970
4971 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004972 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004974 // next check if it's better than any current network we're using for
4975 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004976 if (VDBG) {
4977 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004978 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004979 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004980 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004981 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004982 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004984 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004985 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004986 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004987 affectedNetworks.add(currentNetwork);
4988 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004989 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004990 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004991 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09004992 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004993 if (!newNetwork.addRequest(nri.request)) {
4994 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4995 }
4996 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004997 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004998 // Tell NetworkFactories about the new score, so they can stop
4999 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005000 // TODO - this could get expensive if we have alot of requests for this
5001 // network. Think about if there is a way to reduce this. Push
5002 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005003 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005004 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005005 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005006 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005007 if (currentNetwork != null) {
5008 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5009 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005010 }
5011 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005012 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005013 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5014 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005015 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005016 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5017 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5018 // This means this code doesn't have to handle the case where "currentNetwork" no
5019 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5020 if (DBG) {
5021 log("Network " + newNetwork.name() + " stopped satisfying" +
5022 " request " + nri.request.requestId);
5023 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005024 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005025 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005026 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005027 sendUpdatedScoreToFactories(nri.request, 0);
5028 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005029 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5030 newNetwork.name() +
5031 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005032 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005033 // TODO: Technically, sending CALLBACK_LOST here is
5034 // incorrect if there is a replacement network currently
5035 // connected that can satisfy nri, which is a request
5036 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005037 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5038 // so this code is only incorrect for a network that loses
5039 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005040 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005041 }
5042 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005043 if (isNewDefault) {
5044 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005045 makeDefault(newNetwork);
5046 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005047 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005048 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005049 // Have a new default network, release the transition wakelock in
5050 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005051 }
5052
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005053 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5054 Slog.wtf(TAG, String.format(
5055 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005056 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005057 }
5058 if (newNetwork.getCurrentScore() != score) {
5059 Slog.wtf(TAG, String.format(
5060 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005061 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005062 }
5063
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005064 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005065 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5066 // If the network went from background to foreground or vice versa, we need to update
5067 // its foreground state. It is safe to do this after rematching the requests because
5068 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5069 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005070 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005071 } else {
5072 processListenRequests(newNetwork, false);
5073 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005074
Paul Jensencf4c2c62015-07-01 14:16:32 -04005075 // do this after the default net is switched, but
5076 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005077 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005078
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005079 // Linger any networks that are no longer needed. This should be done after sending the
5080 // available callback for newNetwork.
5081 for (NetworkAgentInfo nai : affectedNetworks) {
5082 updateLingerState(nai, now);
5083 }
5084 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5085 // does not need to be done in any particular order.
5086 updateLingerState(newNetwork, now);
5087
Paul Jensencf4c2c62015-07-01 14:16:32 -04005088 if (isNewDefault) {
5089 // Maintain the illusion: since the legacy API only
5090 // understands one network at a time, we must pretend
5091 // that the current default network disconnected before
5092 // the new one connected.
5093 if (oldDefaultNetwork != null) {
5094 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5095 oldDefaultNetwork, true);
5096 }
5097 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5098 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5099 notifyLockdownVpn(newNetwork);
5100 }
5101
Robert Greenwalt7b816022014-04-18 15:25:25 -07005102 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005103 // Notify battery stats service about this network, both the normal
5104 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005105 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005106 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005107 final IBatteryStats bs = BatteryStatsService.getService();
5108 final int type = newNetwork.networkInfo.getType();
5109
5110 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5111 bs.noteNetworkInterfaceType(baseIface, type);
5112 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5113 final String stackedIface = stacked.getInterfaceName();
5114 bs.noteNetworkInterfaceType(stackedIface, type);
5115 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5116 }
5117 } catch (RemoteException ignored) {
5118 }
5119
Robert Greenwalt152ed372014-12-17 17:19:53 -08005120 // This has to happen after the notifyNetworkCallbacks as that tickles each
5121 // ConnectivityManager instance so that legacy requests correctly bind dns
5122 // requests to this network. The legacy users are listening for this bcast
5123 // and will generally do a dns request so they can ensureRouteToHost and if
5124 // they do that before the callbacks happen they'll use the default network.
5125 //
5126 // TODO: Is there still a race here? We send the broadcast
5127 // after sending the callback, but if the app can receive the
5128 // broadcast before the callback, it might still break.
5129 //
5130 // This *does* introduce a race where if the user uses the new api
5131 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5132 // they may get old info. Reverse this after the old startUsing api is removed.
5133 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005134 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5135 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005136 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005137 // legacy type tracker filters out repeat adds
5138 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5139 }
5140 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005141
5142 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5143 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5144 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5145 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5146 if (newNetwork.isVPN()) {
5147 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5148 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005149 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005150 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5151 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005152 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005153 if (nai.getLingerExpiry() > 0) {
5154 // This network has active linger timers and no requests, but is not
5155 // lingering. Linger it.
5156 //
5157 // One way (the only way?) this can happen if this network is unvalidated
5158 // and became unneeded due to another network improving its score to the
5159 // point where this network will no longer be able to satisfy any requests
5160 // even if it validates.
5161 updateLingerState(nai, now);
5162 } else {
5163 if (DBG) log("Reaping " + nai.name());
5164 teardownUnneededNetwork(nai);
5165 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005166 }
5167 }
5168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169 }
5170
Paul Jensen1c7ba022015-06-16 14:27:36 -04005171 /**
5172 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5173 * being disconnected.
5174 * @param changed If only one Network's score or capabilities have been modified since the last
5175 * time this function was called, pass this Network in this argument, otherwise pass
5176 * null.
5177 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5178 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5179 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5180 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5181 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005182 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005183 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005184 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5185 // to avoid the slowness. It is not simply enough to process just "changed", for
5186 // example in the case where "changed"'s score decreases and another network should begin
5187 // satifying a NetworkRequest that "changed" currently satisfies.
5188
5189 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5190 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5191 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005192 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005193 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005194 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005195 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005196 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5197 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5198 // Rematch higher scoring networks first to prevent requests first matching a lower
5199 // scoring network and then a higher scoring network, which could produce multiple
5200 // callbacks and inadvertently unlinger networks.
5201 Arrays.sort(nais);
5202 for (NetworkAgentInfo nai : nais) {
5203 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005204 // Only reap the last time through the loop. Reaping before all rematching
5205 // is complete could incorrectly teardown a network that hasn't yet been
5206 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005207 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005208 : ReapUnvalidatedNetworks.REAP,
5209 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005210 }
5211 }
5212 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005214 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005215 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005216 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005217 // For now only update icons for default connection.
5218 // TODO: Update WiFi and cellular icons separately. b/17237507
5219 if (!isDefaultNetwork(nai)) return;
5220
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005221 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005222 // Don't repeat publish.
5223 if (newInetCondition == mDefaultInetConditionPublished) return;
5224
5225 mDefaultInetConditionPublished = newInetCondition;
5226 sendInetConditionBroadcast(nai.networkInfo);
5227 }
5228
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005229 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005230 synchronized (mVpns) {
5231 if (mLockdownTracker != null) {
5232 if (nai != null && nai.isVPN()) {
5233 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5234 } else {
5235 mLockdownTracker.onNetworkInfoChanged();
5236 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005237 }
5238 }
5239 }
5240
Robert Greenwalt7b816022014-04-18 15:25:25 -07005241 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005242 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005243 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005244 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005245 synchronized (networkAgent) {
5246 oldInfo = networkAgent.networkInfo;
5247 networkAgent.networkInfo = newInfo;
5248 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005249 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005250
Robert Greenwalt7b816022014-04-18 15:25:25 -07005251 if (DBG) {
5252 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5253 (oldInfo == null ? "null" : oldInfo.getState()) +
5254 " to " + state);
5255 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005256
Robin Lee585e2482016-05-01 23:00:00 +01005257 if (!networkAgent.created
5258 && (state == NetworkInfo.State.CONNECTED
5259 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005260
5261 // A network that has just connected has zero requests and is thus a foreground network.
5262 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5263
Robert Greenwalt7b816022014-04-18 15:25:25 -07005264 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005265 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005266 if (networkAgent.isVPN()) {
5267 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005268 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5269 (networkAgent.networkMisc == null ||
5270 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005271 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005272 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005273 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005274 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005275 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005276 loge("Error creating network " + networkAgent.network.netId + ": "
5277 + e.getMessage());
5278 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005279 }
Paul Jenseneec75412014-08-04 12:21:19 -04005280 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005281 }
5282
5283 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5284 networkAgent.everConnected = true;
5285
Robert Greenwalt7b816022014-04-18 15:25:25 -07005286 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005287 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005288
Paul Jensenca8f16a2014-05-09 12:47:55 -04005289 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005290 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005291
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005292 if (networkAgent.isVPN()) {
5293 // Temporarily disable the default proxy (not global).
5294 synchronized (mProxyLock) {
5295 if (!mDefaultProxyDisabled) {
5296 mDefaultProxyDisabled = true;
5297 if (mGlobalProxy == null && mDefaultProxy != null) {
5298 sendProxyBroadcast(null);
5299 }
5300 }
5301 }
5302 // TODO: support proxy per network.
5303 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005304
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005305 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5306 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5307 // capabilities, so it only needs to be done once on initial connect, not every time the
5308 // network's capabilities change. Note that we do this before rematching the network,
5309 // so we could decide to tear it down immediately afterwards. That's fine though - on
5310 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5311 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005312 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005313
Paul Jensen2161a8e2014-09-11 11:00:39 -04005314 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005315 final long now = SystemClock.elapsedRealtime();
5316 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005317
5318 // This has to happen after matching the requests, because callbacks are just requests.
5319 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005320 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005321 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005322 if (networkAgent.isVPN()) {
5323 synchronized (mProxyLock) {
5324 if (mDefaultProxyDisabled) {
5325 mDefaultProxyDisabled = false;
5326 if (mGlobalProxy == null && mDefaultProxy != null) {
5327 sendProxyBroadcast(mDefaultProxy);
5328 }
5329 }
5330 }
5331 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005332 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5333 state == NetworkInfo.State.SUSPENDED) {
5334 // going into or coming out of SUSPEND: rescore and notify
5335 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005336 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005337 }
5338 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5339 ConnectivityManager.CALLBACK_SUSPENDED :
5340 ConnectivityManager.CALLBACK_RESUMED));
5341 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005342 }
5343 }
5344
Robert Greenwaltac96c522014-06-03 16:43:57 -07005345 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005346 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005347 if (score < 0) {
5348 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5349 "). Bumping score to min of 0");
5350 score = 0;
5351 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005352
Paul Jensen2161a8e2014-09-11 11:00:39 -04005353 final int oldScore = nai.getCurrentScore();
5354 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005355
Paul Jensen85cf78e2015-06-25 13:25:07 -04005356 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005357
Paul Jensenc8b9a742014-09-30 15:37:41 -04005358 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005359 }
5360
Erik Klinec75d4fa2017-02-15 19:59:17 +09005361 // Notify only this one new request of the current state. Transfer all the
5362 // current state by calling NetworkCapabilities and LinkProperties callbacks
5363 // so that callers can be guaranteed to have as close to atomicity in state
5364 // transfer as can be supported by this current API.
5365 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005366 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005367 if (nri.mPendingIntent != null) {
5368 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5369 // Attempt no subsequent state pushes where intents are involved.
5370 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005371 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005372
5373 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5374 // Whether a network is currently suspended is also an important
5375 // element of state to be transferred (it would not otherwise be
5376 // delivered by any currently available mechanism).
5377 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5378 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5379 }
5380 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5381 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005382 }
5383
Robert Greenwalt8d482522015-06-24 13:23:42 -07005384 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005385 // The NetworkInfo we actually send out has no bearing on the real
5386 // state of affairs. For example, if the default connection is mobile,
5387 // and a request for HIPRI has just gone away, we need to pretend that
5388 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5389 // the state to DISCONNECTED, even though the network is of type MOBILE
5390 // and is still connected.
5391 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5392 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005393 if (state != DetailedState.DISCONNECTED) {
5394 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005395 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005396 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005397 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005398 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5399 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5401 if (info.isFailover()) {
5402 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5403 nai.networkInfo.setFailover(false);
5404 }
5405 if (info.getReason() != null) {
5406 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5407 }
5408 if (info.getExtraInfo() != null) {
5409 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5410 }
5411 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005412 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005413 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005414 if (newDefaultAgent != null) {
5415 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5416 newDefaultAgent.networkInfo);
5417 } else {
5418 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5419 }
5420 }
5421 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5422 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005423 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005424 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005425 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005426 }
5427 }
5428 }
5429
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005430 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005431 if (VDBG) {
5432 String notification = ConnectivityManager.getCallbackName(notifyType);
5433 log("notifyType " + notification + " for " + networkAgent.name());
5434 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005435 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5436 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005437 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5438 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005439 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5440 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005441 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005442 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005443 } else {
5444 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5445 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005446 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005448
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005449 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5450 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5451 }
5452
Jeff Sharkey69736342014-12-08 14:50:12 -08005453 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005454 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5455 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005456 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005457 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005458 try {
5459 mStatsService.forceUpdateIfaces();
5460 } catch (Exception ignored) {
5461 }
5462 }
5463
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005464 @Override
5465 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005466 int user = UserHandle.getUserId(Binder.getCallingUid());
5467 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005468 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005469 return mVpns.get(user).addAddress(address, prefixLength);
5470 }
5471 }
5472
5473 @Override
5474 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005475 int user = UserHandle.getUserId(Binder.getCallingUid());
5476 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005477 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005478 return mVpns.get(user).removeAddress(address, prefixLength);
5479 }
5480 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005481
5482 @Override
5483 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005484 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005485 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005486 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005487 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005488 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005489 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005490 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005491 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005492 }
5493 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005494 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005495
5496 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005497 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005498 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005499 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005500 }
5501
5502 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005503 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5504 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5505 enforceKeepalivePermission();
5506 mKeepaliveTracker.startNattKeepalive(
5507 getNetworkAgentInfoForNetwork(network),
5508 intervalSeconds, messenger, binder,
5509 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5510 }
5511
5512 @Override
5513 public void stopKeepalive(Network network, int slot) {
5514 mHandler.sendMessage(mHandler.obtainMessage(
5515 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5516 }
5517
5518 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005519 public void factoryReset() {
5520 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005521
5522 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5523 return;
5524 }
5525
Robin Lee3b3dd942015-05-12 18:14:58 +01005526 final int userId = UserHandle.getCallingUserId();
5527
Stuart Scottf1fb3972015-04-02 18:00:02 -07005528 // Turn airplane mode off
5529 setAirplaneMode(false);
5530
Stuart Scotte3e314d2015-04-20 14:07:45 -07005531 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5532 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005533 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005534 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005535 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005536 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005537 }
5538
Stuart Scotte3e314d2015-04-20 14:07:45 -07005539 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005540 // Remove always-on package
5541 synchronized (mVpns) {
5542 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5543 if (alwaysOnPackage != null) {
5544 setAlwaysOnVpnPackage(userId, null, false);
5545 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5546 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005547
Hugo Benichi69744342017-11-27 10:57:16 +09005548 // Turn Always-on VPN off
5549 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5550 final long ident = Binder.clearCallingIdentity();
5551 try {
5552 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5553 mLockdownEnabled = false;
5554 setLockdownTracker(null);
5555 } finally {
5556 Binder.restoreCallingIdentity(ident);
5557 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005558 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005559
Hugo Benichi69744342017-11-27 10:57:16 +09005560 // Turn VPN off
5561 VpnConfig vpnConfig = getVpnConfig(userId);
5562 if (vpnConfig != null) {
5563 if (vpnConfig.legacy) {
5564 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5565 } else {
5566 // Prevent this app (packagename = vpnConfig.user) from initiating
5567 // VPN connections in the future without user intervention.
5568 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005569
Hugo Benichi69744342017-11-27 10:57:16 +09005570 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5571 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005572 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005573 }
5574 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005575
5576 Settings.Global.putString(mContext.getContentResolver(),
5577 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005578 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005579
5580 @VisibleForTesting
5581 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5582 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5583 return new NetworkMonitor(context, handler, nai, defaultRequest);
5584 }
Erik Kline48f12f22016-04-14 17:30:59 +09005585
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005586 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005587 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5588 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005589 }
5590
5591 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005592 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5593 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5594 }
5595
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005596 @VisibleForTesting
5597 public boolean hasService(String name) {
5598 return ServiceManager.checkService(name) != null;
5599 }
5600
Hugo Benichi64901e52017-10-19 14:42:40 +09005601 @VisibleForTesting
5602 protected IpConnectivityMetrics.Logger metricsLogger() {
5603 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5604 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005605 }
5606
5607 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005608 int[] transports = nai.networkCapabilities.getTransportTypes();
5609 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005610 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005611
5612 private static boolean toBool(int encodedBoolean) {
5613 return encodedBoolean != 0; // Only 0 means false.
5614 }
5615
5616 private static int encodeBool(boolean b) {
5617 return b ? 1 : 0;
5618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619}