blob: b19e482115e22dc3af3bc6f7f822585b8d016b91 [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
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700227 private boolean mLockdownEnabled;
228 private LockdownVpnTracker mLockdownTracker;
229
Erik Klineda4bfa82015-04-30 12:58:40 +0900230 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700232 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700233 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800235 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
237 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700238 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700240 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800241 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900243 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700244
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700245 private String mCurrentTcpBufferSizes;
246
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700247 private static final int ENABLED = 1;
248 private static final int DISABLED = 0;
249
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900250 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900251 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
252 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900253
Paul Jensenb10e37f2014-11-25 12:33:08 -0500254 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400255 // Tear down networks that have no chance (e.g. even if validated) of becoming
256 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500257 // all networks have been rematched against all NetworkRequests.
258 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400259 // Don't reap networks. This should be passed when some networks have not yet been
260 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 DONT_REAP
262 };
263
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900264 private enum UnneededFor {
265 LINGER, // Determine whether this network is unneeded and should be lingered.
266 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
267 }
268
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270 * used internally to change our mobile data enabled flag
271 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700272 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273
274 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700276 * from one net to another. Clear happens when we get a new
277 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
278 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700280 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700281
Robert Greenwalt434203a2010-10-11 16:00:27 -0700282 /**
283 * used internally to reload global proxy settings
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700287 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400288 * PAC manager has received new port.
289 */
290 private static final int EVENT_PROXY_HAS_CHANGED = 16;
291
Robert Greenwalte049c232014-04-11 15:53:27 -0700292 /**
293 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700294 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700295 */
296 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
297
Robert Greenwalt7b816022014-04-18 15:25:25 -0700298 /**
299 * used internally when registering NetworkAgents
300 * obj = Messenger
301 */
302 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
303
Robert Greenwalt9258c642014-03-26 16:47:06 -0700304 /**
305 * used to add a network request
306 * includes a NetworkRequestInfo
307 */
308 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
309
310 /**
311 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900312 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700313 * cancel it.
314 * includes a NetworkRequestInfo
315 */
316 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
317
318 /**
319 * used to add a network listener - no request
320 * includes a NetworkRequestInfo
321 */
322 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
323
324 /**
325 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400326 * arg1 = UID of caller
327 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700328 */
329 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
330
Robert Greenwalta67be032014-05-16 15:49:14 -0700331 /**
332 * used internally when registering NetworkFactories
333 * obj = Messenger
334 */
335 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
336
Robert Greenwalt27711812014-06-25 16:45:57 -0700337 /**
338 * used internally to expire a wakelock when transitioning
339 * from one net to another. Expire happens when we fail to find
340 * a new network (typically after 1 minute) -
341 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
342 * a replacement network.
343 */
344 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
345
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700346 /**
347 * Used internally to indicate the system is ready.
348 */
349 private static final int EVENT_SYSTEM_READY = 25;
350
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800351 /**
352 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400353 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800354 */
355 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
356
357 /**
358 * used to remove a pending intent and its associated network request.
359 * arg1 = UID of caller
360 * obj = PendingIntent
361 */
362 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
363
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900364 /**
365 * used to specify whether a network should be used even if unvalidated.
366 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
367 * arg2 = whether to remember this choice in the future (1 or 0)
368 * obj = network
369 */
370 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
371
372 /**
373 * used to ask the user to confirm a connection to an unvalidated network.
374 * obj = network
375 */
376 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700377
Erik Klineda4bfa82015-04-30 12:58:40 +0900378 /**
379 * used internally to (re)configure mobile data always-on settings.
380 */
381 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
382
Paul Jensen694f2b82015-06-17 14:15:39 -0400383 /**
384 * used to add a network listener with a pending intent
385 * obj = NetworkRequestInfo
386 */
387 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
388
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900389 /**
390 * used to specify whether a network should not be penalized when it becomes unvalidated.
391 */
392 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
393
394 /**
395 * used to trigger revalidation of a network.
396 */
397 private static final int EVENT_REVALIDATE_NETWORK = 36;
398
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900399 private static String eventName(int what) {
400 return sMagicDecoderRing.get(what, Integer.toString(what));
401 }
402
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900403 /** Handler thread used for both of the handlers below. */
404 @VisibleForTesting
405 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700406 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700407 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700408 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700409 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700410
Mike Lockwood0f79b542009-08-14 14:18:49 -0400411 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800412 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400413
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700414 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800416 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700417
Robert Greenwalt434203a2010-10-11 16:00:27 -0700418 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400419 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700420 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700421 private boolean mDefaultProxyDisabled = false;
422
Robert Greenwalt434203a2010-10-11 16:00:27 -0700423 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400424 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425
Jason Monk602b2322013-07-03 17:04:33 -0400426 private PacManager mPacManager = null;
427
Erik Klineda4bfa82015-04-30 12:58:40 +0900428 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400430 private UserManager mUserManager;
431
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700432 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700433 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700434
Robert Greenwalt50393202011-06-21 17:26:14 -0700435 // the set of network types that can only be enabled by system/sig apps
436 List mProtectedNetworks;
437
John Spurlockbf991a82013-06-24 14:20:23 -0400438 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700439
Wink Savilleab9321d2013-06-29 21:10:57 -0700440 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400441
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900442 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900443 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900444 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900445
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700446 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
447 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700448 private final static int MAX_NET_ID = 65535;
449 private int mNextNetId = MIN_NET_ID;
450
Robert Greenwalt34524f02014-05-18 16:22:10 -0700451 // sequence number of NetworkRequests
452 private int mNextNetworkRequestId = 1;
453
Erik Kline7523eb32015-07-09 18:24:03 +0900454 // NetworkRequest activity String log entries.
455 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
456 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
457
Hugo Benichic2ae2872016-07-11 11:05:12 +0900458 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900459 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900460 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
461
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900462 private static final int MAX_WAKELOCK_LOGS = 20;
463 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900464 private int mTotalWakelockAcquisitions = 0;
465 private int mTotalWakelockReleases = 0;
466 private long mTotalWakelockDurationMs = 0;
467 private long mMaxWakelockDurationMs = 0;
468 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900469
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700470 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
471 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400472 private static class ValidationLog {
473 final Network mNetwork;
474 final String mNetworkExtraInfo;
475 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700476
Paul Jensen0808eb82016-06-03 13:51:21 -0400477 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
478 mNetwork = network;
479 mNetworkExtraInfo = networkExtraInfo;
480 mLog = log;
481 }
482 }
483 private final ArrayDeque<ValidationLog> mValidationLogs =
484 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
485
486 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900487 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
489 mValidationLogs.removeLast();
490 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400491 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700492 }
493 }
494
Hugo Benichif9fdf872016-07-28 17:53:06 +0900495 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900496
Erik Kline065ab6e2016-10-02 18:02:14 +0900497 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900498 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900499
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 /**
501 * Implements support for the legacy "one network per network type" model.
502 *
503 * We used to have a static array of NetworkStateTrackers, one for each
504 * network type, but that doesn't work any more now that we can have,
505 * for example, more that one wifi network. This class stores all the
506 * NetworkAgentInfo objects that support a given type, but the legacy
507 * API will only see the first one.
508 *
509 * It serves two main purposes:
510 *
511 * 1. Provide information about "the network for a given type" (since this
512 * API only supports one).
513 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
514 * the first network for a given type changes, or if the default network
515 * changes.
516 */
517 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900519 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 /**
523 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
524 * Each list holds references to all NetworkAgentInfos that are used to
525 * satisfy requests for that network type.
526 *
527 * This array is built out at startup such that an unsupported network
528 * doesn't get an ArrayList instance, making this a tristate:
529 * unsupported, supported but not active and active.
530 *
531 * The actual lists are populated when we scan the network types that
532 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900533 *
534 * Threading model:
535 * - addSupportedType() is only called in the constructor
536 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
537 * They are therefore not thread-safe with respect to each other.
538 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
539 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
540 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700541 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900542 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700543
544 public LegacyTypeTracker() {
545 mTypeLists = (ArrayList<NetworkAgentInfo>[])
546 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
547 }
548
549 public void addSupportedType(int type) {
550 if (mTypeLists[type] != null) {
551 throw new IllegalStateException(
552 "legacy list for type " + type + "already initialized");
553 }
554 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
555 }
556
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 public boolean isTypeSupported(int type) {
558 return isNetworkTypeValid(type) && mTypeLists[type] != null;
559 }
560
561 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 synchronized (mTypeLists) {
563 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
564 return mTypeLists[type].get(0);
565 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900567 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700568 }
569
Robert Greenwalt8d482522015-06-24 13:23:42 -0700570 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900571 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900574 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 }
577 }
578
579 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700580 public void add(int type, NetworkAgentInfo nai) {
581 if (!isTypeSupported(type)) {
582 return; // Invalid network type.
583 }
584 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
585
586 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
587 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 return;
589 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900590 synchronized (mTypeLists) {
591 list.add(nai);
592 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900593
594 // 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 +0900595 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900596 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700597 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
598 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700599 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 }
601
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
605 if (list == null || list.isEmpty()) {
606 return;
607 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900608 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609
Hugo Benichi78caa2582016-06-21 09:48:07 +0900610 synchronized (mTypeLists) {
611 if (!list.remove(nai)) {
612 return;
613 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 }
615
Robert Greenwalt8d482522015-06-24 13:23:42 -0700616 final DetailedState state = DetailedState.DISCONNECTED;
617
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900618 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 maybeLogBroadcast(nai, state, type, wasDefault);
620 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621 }
622
623 if (!list.isEmpty() && wasFirstNetwork) {
624 if (DBG) log("Other network available for type " + type +
625 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
628 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900629 }
630 }
631
632 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
634 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700635 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700637 }
638 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700639
Robert Greenwalt8d482522015-06-24 13:23:42 -0700640 // send out another legacy broadcast - currently only used for suspend/unsuspend
641 // toggle
642 public void update(NetworkAgentInfo nai) {
643 final boolean isDefault = isDefaultNetwork(nai);
644 final DetailedState state = nai.networkInfo.getDetailedState();
645 for (int type = 0; type < mTypeLists.length; type++) {
646 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700647 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900648 final boolean isFirst = contains && (nai == list.get(0));
649 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700650 maybeLogBroadcast(nai, state, type, isDefault);
651 sendLegacyNetworkBroadcast(nai, state, type);
652 }
653 }
654 }
655
Lorenzo Colittia793a672014-07-31 23:20:17 +0900656 private String naiToString(NetworkAgentInfo nai) {
657 String name = (nai != null) ? nai.name() : "null";
658 String state = (nai.networkInfo != null) ?
659 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
660 "???/???";
661 return name + " " + state;
662 }
663
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700664 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 pw.println("mLegacyTypeTracker:");
666 pw.increaseIndent();
667 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700670 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900671 pw.println();
672 pw.println("Current state:");
673 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900674 synchronized (mTypeLists) {
675 for (int type = 0; type < mTypeLists.length; type++) {
676 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
677 for (NetworkAgentInfo nai : mTypeLists[type]) {
678 pw.println(type + " " + naiToString(nai));
679 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900680 }
681 }
682 pw.decreaseIndent();
683 pw.decreaseIndent();
684 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700685 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700686 }
687 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
688
Jeff Sharkey899223b2012-08-04 15:24:58 -0700689 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700690 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900691 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
692 }
693
694 @VisibleForTesting
695 protected ConnectivityService(Context context, INetworkManagementService netManager,
696 INetworkStatsService statsService, INetworkPolicyManager policyManager,
697 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800698 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800699
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900700 mSystemProperties = getSystemProperties();
701
Hugo Benichif9fdf872016-07-28 17:53:06 +0900702 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900703 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900704 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900705 mNetworkRequests.put(mDefaultRequest, defaultNRI);
706 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900707
708 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900709 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700710
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900711 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900712 mHandlerThread.start();
713 mHandler = new InternalHandler(mHandlerThread.getLooper());
714 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700715
Jeremy Joslin79294842014-12-03 17:15:28 -0800716 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
717 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
718
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900719 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900720
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700722 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800723 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900725 mPolicyManagerInternal = checkNotNull(
726 LocalServices.getService(NetworkPolicyManagerInternal.class),
727 "missing NetworkPolicyManagerInternal");
728
Jeff Sharkey82f85212012-08-24 11:17:25 -0700729 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700730 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700731
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900733 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 } catch (RemoteException e) {
735 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700736 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 }
738
739 final PowerManager powerManager = (PowerManager) context.getSystemService(
740 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700741 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
742 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
743 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800744 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700746 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700747
Wink Saville51f456f2013-04-23 14:26:51 -0700748 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900749 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700750 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751 String[] naStrings = context.getResources().getStringArray(
752 com.android.internal.R.array.networkAttributes);
753 for (String naString : naStrings) {
754 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700755 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700756 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700757 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800758 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700759 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700761 }
Wink Saville51f456f2013-04-23 14:26:51 -0700762 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
763 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
764 n.type);
765 continue;
766 }
Wink Saville975c8482011-04-07 14:23:45 -0700767 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800768 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700769 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700770 continue;
771 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700772 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700773
Wink Saville975c8482011-04-07 14:23:45 -0700774 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700775 mNetworksDefined++;
776 } catch(Exception e) {
777 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700778 }
779 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700780
781 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
782 if (mNetConfigs[TYPE_VPN] == null) {
783 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
784 // don't need to add TYPE_VPN to mNetConfigs.
785 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
786 mNetworksDefined++; // used only in the log() statement below.
787 }
788
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900789 // Do the same for Ethernet, since it's often not specified in the configs, although many
790 // devices can use it via USB host adapters.
791 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
792 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
793 mNetworksDefined++;
794 }
795
Wink Saville5e56bc52013-07-29 15:00:57 -0700796 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700797
Robert Greenwalt50393202011-06-21 17:26:14 -0700798 mProtectedNetworks = new ArrayList<Integer>();
799 int[] protectedNetworks = context.getResources().getIntArray(
800 com.android.internal.R.array.config_protectedNetworks);
801 for (int p : protectedNetworks) {
802 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
803 mProtectedNetworks.add(p);
804 } else {
805 if (DBG) loge("Ignoring protectedNetwork " + p);
806 }
807 }
808
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900809 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
810 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700811
Erik Kline47222fc2017-04-30 19:36:15 +0900812 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800813
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700814 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
815
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700816 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700817 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100818 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700819 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700820 intentFilter.addAction(Intent.ACTION_USER_ADDED);
821 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000822 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700823 mContext.registerReceiverAsUser(
824 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000825 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
826 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900827
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700828 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700829 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700830 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700831 } catch (RemoteException e) {
832 loge("Error registering observer :" + e);
833 }
834
Erik Klineda4bfa82015-04-30 12:58:40 +0900835 mSettingsObserver = new SettingsObserver(mContext, mHandler);
836 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800837
John Spurlockbf991a82013-06-24 14:20:23 -0400838 mDataConnectionStats = new DataConnectionStats(mContext);
839 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400840
Jason Monkdecd2952013-10-10 14:02:51 -0400841 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700842
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400843 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900844
845 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900846 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
847 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900848
849 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
850 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
851 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
852 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
853 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
854 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
855 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900856
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900857 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900858 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900859 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700861
Erik Kline47222fc2017-04-30 19:36:15 +0900862 private Tethering makeTethering() {
863 // TODO: Move other elements into @Overridden getters.
864 final TetheringDependencies deps = new TetheringDependencies();
865 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
866 IoThread.get().getLooper(), new MockableSystemProperties(),
867 deps);
868 }
869
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900870 private NetworkRequest createInternetRequestForTransport(
871 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900873 netCap.addCapability(NET_CAPABILITY_INTERNET);
874 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900875 if (transportType > -1) {
876 netCap.addTransportType(transportType);
877 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900878 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 }
880
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900881 // Used only for testing.
882 // TODO: Delete this and either:
883 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
884 // changing ContentResolver to make registerContentObserver non-final).
885 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
886 // by subclassing SettingsObserver.
887 @VisibleForTesting
888 void updateMobileDataAlwaysOn() {
889 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
890 }
891
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900893 final boolean enable = toBool(Settings.Global.getInt(
894 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900895 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
896 if (enable == isEnabled) {
897 return; // Nothing to do.
898 }
899
900 if (enable) {
901 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900902 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900903 } else {
904 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
905 }
906 }
907
908 private void registerSettingsCallbacks() {
909 // Watch for global HTTP proxy changes.
910 mSettingsObserver.observe(
911 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
912 EVENT_APPLY_GLOBAL_HTTP_PROXY);
913
914 // Watch for whether or not to keep mobile data always on.
915 mSettingsObserver.observe(
916 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
917 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
918 }
919
Robert Greenwalt34524f02014-05-18 16:22:10 -0700920 private synchronized int nextNetworkRequestId() {
921 return mNextNetworkRequestId++;
922 }
923
Paul Jensen67b0b072015-06-10 11:22:17 -0400924 @VisibleForTesting
925 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400926 synchronized (mNetworkForNetId) {
927 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
928 int netId = mNextNetId;
929 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
930 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500931 if (!mNetIdInUse.get(netId)) {
932 mNetIdInUse.put(netId, true);
933 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400934 }
935 }
936 }
937 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700938 }
939
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600940 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600942 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
943 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 state = nai.getNetworkState();
946 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600948 final NetworkInfo info = new NetworkInfo(networkType, 0,
949 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
951 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700952 final NetworkCapabilities capabilities = new NetworkCapabilities();
953 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
954 !info.isRoaming());
955 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600956 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600958 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600959 return state;
960 } else {
961 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400963 }
964
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
966 if (network == null) {
967 return null;
968 }
969 synchronized (mNetworkForNetId) {
970 return mNetworkForNetId.get(network.netId);
971 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600972 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900974 private Network[] getVpnUnderlyingNetworks(int uid) {
975 if (!mLockdownEnabled) {
976 int user = UserHandle.getUserId(uid);
977 synchronized (mVpns) {
978 Vpn vpn = mVpns.get(user);
979 if (vpn != null && vpn.appliesToUid(uid)) {
980 return vpn.getUnderlyingNetworks();
981 }
982 }
983 }
984 return null;
985 }
986
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800987 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400988 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800989
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900990 final Network[] networks = getVpnUnderlyingNetworks(uid);
991 if (networks != null) {
992 // getUnderlyingNetworks() returns:
993 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
994 // empty array => the VPN explicitly said "no default network".
995 // non-empty array => the VPN specified one or more default networks; we use the
996 // first one.
997 if (networks.length > 0) {
998 nai = getNetworkAgentInfoForNetwork(networks[0]);
999 } else {
1000 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001001 }
1002 }
1003
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001005 return nai.getNetworkState();
1006 } else {
1007 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001009 }
1010
1011 /**
1012 * Check if UID should be blocked from using the network with the given LinkProperties.
1013 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1015 boolean ignoreBlocked) {
1016 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001017 if (ignoreBlocked) {
1018 return false;
1019 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001020 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001021 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1022 if (isSystem(uid)) {
1023 return false;
1024 }
Robin Lee17e61832016-05-09 13:46:28 +01001025 synchronized (mVpns) {
1026 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1027 if (vpn != null && vpn.isBlockingUid(uid)) {
1028 return true;
1029 }
1030 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001031 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001032 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
1034
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001035 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001036 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1037 return;
1038 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001039 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001040 synchronized (mBlockedAppUids) {
1041 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001042 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001043 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001044 blocked = false;
1045 } else {
1046 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001047 }
1048 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001049 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1050 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1051 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001052 }
1053
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001055 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1056 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001057 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001059 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1061
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001062 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001063 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 if (mLockdownTracker != null) {
1066 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001067 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 }
1069
1070 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 * Return NetworkInfo for the active (i.e., connected) network interface.
1072 * It is assumed that at most one network is active at a time. If more
1073 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001074 * @return the info for the active network, or {@code null} if none is
1075 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001077 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1084 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086
Paul Jensen31a94f42015-02-13 14:18:39 -05001087 @Override
1088 public Network getActiveNetwork() {
1089 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001091 }
1092
1093 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001094 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001095 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001097 }
1098
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001099 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001100 final int user = UserHandle.getUserId(uid);
1101 int vpnNetId = NETID_UNSET;
1102 synchronized (mVpns) {
1103 final Vpn vpn = mVpns.get(user);
1104 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1105 }
1106 NetworkAgentInfo nai;
1107 if (vpnNetId != NETID_UNSET) {
1108 synchronized (mNetworkForNetId) {
1109 nai = mNetworkForNetId.get(vpnNetId);
1110 }
1111 if (nai != null) return nai.network;
1112 }
1113 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 if (nai != null
1115 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1116 nai = null;
1117 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001118 return nai != null ? nai.network : null;
1119 }
1120
Lorenzo Colitti18660282016-07-04 12:55:44 +09001121 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001122 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1123 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001124 final int uid = Binder.getCallingUid();
1125 NetworkState state = getUnfilteredActiveNetworkState(uid);
1126 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001127 }
1128
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001129 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001131 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001132 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001133 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001135 }
1136
1137 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 public NetworkInfo getNetworkInfo(int networkType) {
1139 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001141 if (getVpnUnderlyingNetworks(uid) != null) {
1142 // A VPN is active, so we may need to return one of its underlying networks. This
1143 // information is not available in LegacyTypeTracker, so we have to get it from
1144 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001146 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001148 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001149 }
1150 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001151 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 return state.networkInfo;
1163 } else {
1164 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 }
1167
1168 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 public NetworkInfo[] getAllNetworkInfo() {
1170 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001171 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001172 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1173 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 NetworkInfo info = getNetworkInfo(networkType);
1175 if (info != null) {
1176 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001179 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
1181
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001182 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001183 public Network getNetworkForType(int networkType) {
1184 enforceAccessPermission();
1185 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001186 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1187 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001188 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001189 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001191 }
1192
1193 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001194 public Network[] getAllNetworks() {
1195 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001197 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001198 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001199 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001201 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001203 }
1204
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001205 @Override
1206 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1207 // The basic principle is: if an app's traffic could possibly go over a
1208 // network, without the app doing anything multinetwork-specific,
1209 // (hence, by "default"), then include that network's capabilities in
1210 // the array.
1211 //
1212 // In the normal case, app traffic only goes over the system's default
1213 // network connection, so that's the only network returned.
1214 //
1215 // With a VPN in force, some app traffic may go into the VPN, and thus
1216 // over whatever underlying networks the VPN specifies, while other app
1217 // traffic may go over the system default network (e.g.: a split-tunnel
1218 // VPN, or an app disallowed by the VPN), so the set of networks
1219 // returned includes the VPN's underlying networks and the system
1220 // default.
1221 enforceAccessPermission();
1222
1223 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1224
1225 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001226 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001227 if (nc != null) {
1228 result.put(nai.network, nc);
1229 }
1230
1231 if (!mLockdownEnabled) {
1232 synchronized (mVpns) {
1233 Vpn vpn = mVpns.get(userId);
1234 if (vpn != null) {
1235 Network[] networks = vpn.getUnderlyingNetworks();
1236 if (networks != null) {
1237 for (Network network : networks) {
1238 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001239 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001240 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001241 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001242 }
1243 }
1244 }
1245 }
1246 }
1247 }
1248
1249 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1250 out = result.values().toArray(out);
1251 return out;
1252 }
1253
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001254 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001255 public boolean isNetworkSupported(int networkType) {
1256 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001258 }
1259
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001260 /**
1261 * Return LinkProperties for the active (i.e., connected) default
1262 * network interface. It is assumed that at most one default network
1263 * is active at a time. If more than one is active, it is indeterminate
1264 * which will be returned.
1265 * @return the ip properties for the active network, or {@code null} if
1266 * none is active
1267 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001269 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001270 enforceAccessPermission();
1271 final int uid = Binder.getCallingUid();
1272 NetworkState state = getUnfilteredActiveNetworkState(uid);
1273 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001274 }
1275
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001276 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001277 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001278 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001279 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1280 if (nai != null) {
1281 synchronized (nai) {
1282 return new LinkProperties(nai.linkProperties);
1283 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001284 }
1285 return null;
1286 }
1287
Robert Greenwalt12e67352014-05-13 21:41:06 -07001288 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001289 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001290 public LinkProperties getLinkProperties(Network network) {
1291 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001292 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1293 }
1294
1295 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1296 if (nai == null) {
1297 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001298 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001299 synchronized (nai) {
1300 return new LinkProperties(nai.linkProperties);
1301 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001302 }
1303
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001304 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 if (nai != null) {
1306 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001307 if (nai.networkCapabilities != null) {
1308 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001309 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001310 }
1311 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001312 return null;
1313 }
1314
1315 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001316 public NetworkCapabilities getNetworkCapabilities(Network network) {
1317 enforceAccessPermission();
1318 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1319 }
1320
1321 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001322 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001323 // Require internal since we're handing out IMSI details
1324 enforceConnectivityInternalPermission();
1325
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001326 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001327 for (Network network : getAllNetworks()) {
1328 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1329 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001330 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001331 }
1332 }
1333 return result.toArray(new NetworkState[result.size()]);
1334 }
1335
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001336 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001337 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001338 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001339 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1340 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1341 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001342 }
1343
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001344 @Override
1345 public boolean isActiveNetworkMetered() {
1346 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001347
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001348 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1349 if (caps != null) {
1350 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1351 } else {
1352 // Always return the most conservative value
1353 return true;
1354 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001355 }
1356
Jeff Sharkey216c1812012-08-05 14:29:23 -07001357 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1358 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001359 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001360 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001361 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001362 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001363 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001364
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001365 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 * Ensure that a network route exists to deliver traffic to the specified
1367 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001368 * @param networkType the type of the network over which traffic to the
1369 * specified host is to be routed
1370 * @param hostAddress the IP address of the host to which the route is
1371 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 * @return {@code true} on success, {@code false} on failure
1373 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001374 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001375 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001377 if (mProtectedNetworks.contains(networkType)) {
1378 enforceConnectivityInternalPermission();
1379 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001380
Chad Brubakerc0234532014-02-14 13:24:29 -08001381 InetAddress addr;
1382 try {
1383 addr = InetAddress.getByAddress(hostAddress);
1384 } catch (UnknownHostException e) {
1385 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1386 return false;
1387 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001390 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 return false;
1392 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001393
1394 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1395 if (nai == null) {
1396 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1397 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1398 } else {
1399 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1400 }
1401 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001402 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001403
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001404 DetailedState netState;
1405 synchronized (nai) {
1406 netState = nai.networkInfo.getDetailedState();
1407 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001408
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001410 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001411 log("requestRouteToHostAddress on down network "
1412 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001413 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001414 }
1415 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001417
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001418 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001419 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001420 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001421 LinkProperties lp;
1422 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001423 synchronized (nai) {
1424 lp = nai.linkProperties;
1425 netId = nai.network.netId;
1426 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001427 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001428 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1429 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001430 } finally {
1431 Binder.restoreCallingIdentity(token);
1432 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001433 }
1434
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001435 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001436 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001437 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001438 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001439 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001440 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001441 if (bestRoute.getGateway().equals(addr)) {
1442 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001443 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001444 } else {
1445 // if we will connect to this through another route, add a direct route
1446 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001447 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001448 }
1449 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001450 if (DBG) log("Adding legacy route " + bestRoute +
1451 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001452 try {
1453 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1454 } catch (Exception e) {
1455 // never crash - catch them all
1456 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001457 return false;
1458 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001459 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001462 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001463 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001464 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001465 // TODO: notify UID when it has requested targeted updates
1466 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001467 @Override
1468 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001469 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001470 @Override
1471 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001472 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001473 if (restrictBackground) {
1474 log("onRestrictBackgroundChanged(true): disabling tethering");
1475 mTethering.untetherAll();
1476 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001477 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001478 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001479 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001480 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001481 };
1482
Robin Lee3b3dd942015-05-12 18:14:58 +01001483 /**
1484 * Require that the caller is either in the same user or has appropriate permission to interact
1485 * across users.
1486 *
1487 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1488 */
1489 private void enforceCrossUserPermission(int userId) {
1490 if (userId == UserHandle.getCallingUserId()) {
1491 // Not a cross-user call.
1492 return;
1493 }
1494 mContext.enforceCallingOrSelfPermission(
1495 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1496 "ConnectivityService");
1497 }
1498
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001499 private void enforceInternetPermission() {
1500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.INTERNET,
1502 "ConnectivityService");
1503 }
1504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001506 mContext.enforceCallingOrSelfPermission(
1507 android.Manifest.permission.ACCESS_NETWORK_STATE,
1508 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510
1511 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001512 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514
Charles Hea0a87e82017-05-15 17:07:18 +01001515 private void enforceSettingsPermission() {
1516 mContext.enforceCallingOrSelfPermission(
1517 android.Manifest.permission.NETWORK_SETTINGS,
1518 "ConnectivityService");
1519 }
1520
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001521 private void enforceTetherAccessPermission() {
1522 mContext.enforceCallingOrSelfPermission(
1523 android.Manifest.permission.ACCESS_NETWORK_STATE,
1524 "ConnectivityService");
1525 }
1526
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001527 private void enforceConnectivityInternalPermission() {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1530 "ConnectivityService");
1531 }
1532
Hugo Benichi514da602016-07-19 15:59:27 +09001533 private void enforceConnectivityRestrictedNetworksPermission() {
1534 try {
1535 mContext.enforceCallingOrSelfPermission(
1536 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1537 "ConnectivityService");
1538 return;
1539 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1540 enforceConnectivityInternalPermission();
1541 }
1542
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001543 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001544 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001545 }
1546
Lorenzo Colitti18660282016-07-04 12:55:44 +09001547 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001548 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001549 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001550 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001551 }
1552
1553 private void sendInetConditionBroadcast(NetworkInfo info) {
1554 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1555 }
1556
Wink Saville628b0852011-08-04 15:01:58 -07001557 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001558 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001559 info = new NetworkInfo(info);
1560 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001561 }
1562
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001563 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001564 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001565 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 if (info.isFailover()) {
1567 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1568 info.setFailover(false);
1569 }
1570 if (info.getReason() != null) {
1571 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1572 }
1573 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001574 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1575 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001577 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001578 return intent;
1579 }
1580
1581 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1582 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1583 }
1584
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001585 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001586 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1587 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1588 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001589 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001590 final long ident = Binder.clearCallingIdentity();
1591 try {
1592 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1593 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1594 } finally {
1595 Binder.restoreCallingIdentity(ident);
1596 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001597 }
1598
Mike Lockwood0f79b542009-08-14 14:18:49 -04001599 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001600 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001601 if (!mSystemReady) {
1602 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001603 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001604 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001605 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001606 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001607 }
1608
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001609 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001610 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001611 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001612 final NetworkInfo ni = intent.getParcelableExtra(
1613 ConnectivityManager.EXTRA_NETWORK_INFO);
1614 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1615 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1616 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001617 } else {
1618 BroadcastOptions opts = BroadcastOptions.makeBasic();
1619 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1620 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001621 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001622 final IBatteryStats bs = BatteryStatsService.getService();
1623 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001624 bs.noteConnectivityChanged(intent.getIntExtra(
1625 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1626 ni != null ? ni.getState().toString() : "?");
1627 } catch (RemoteException e) {
1628 }
1629 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001630 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001631 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001632 } finally {
1633 Binder.restoreCallingIdentity(ident);
1634 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001635 }
1636 }
1637
1638 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001639 loadGlobalProxy();
1640
Hugo Benichi20035e02017-04-26 14:53:28 +09001641 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001642 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001643 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001644 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001645 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001646 }
1647 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001648 // load the global proxy at startup
1649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001650
Robin Lee244ce8e2016-01-05 18:03:46 +00001651 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1652 // for user to unlock device too.
1653 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001654
Erik Klineda4bfa82015-04-30 12:58:40 +09001655 // Configure whether mobile data is always on.
1656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1657
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001658 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001659
1660 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001664 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001665 *
1666 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001667 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001668 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001669 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1670 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001671
1672 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001673 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001674
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 if (networkAgent.networkCapabilities.hasTransport(
1676 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001677 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1678 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001679 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001680 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 } else if (networkAgent.networkCapabilities.hasTransport(
1682 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001683 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1684 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001685 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001686 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001687 } else {
1688 // do not track any other networks
1689 timeout = 0;
1690 }
1691
Robert Greenwalt7b816022014-04-18 15:25:25 -07001692 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001693 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001694 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001695 } catch (Exception e) {
1696 // You shall not crash!
1697 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001698 }
1699 }
1700 }
1701
1702 /**
1703 * Remove data activity tracking when network disconnects.
1704 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001705 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1706 final String iface = networkAgent.linkProperties.getInterfaceName();
1707 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001708
Robert Greenwalt7b816022014-04-18 15:25:25 -07001709 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1710 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001711 try {
1712 // the call fails silently if no idletimer setup for this interface
1713 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001714 } catch (Exception e) {
1715 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001716 }
1717 }
1718 }
1719
1720 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001721 * Reads the network specific MTU size from reources.
1722 * and set it on it's iface.
1723 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001724 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1725 final String iface = newLp.getInterfaceName();
1726 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001727 if (oldLp == null && mtu == 0) {
1728 // Silently ignore unset MTU value.
1729 return;
1730 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001731 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1732 if (VDBG) log("identical MTU - not setting");
1733 return;
1734 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001735 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001736 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001737 return;
1738 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001739
w1997615afd812014-08-05 15:18:11 -07001740 // Cannot set MTU without interface name
1741 if (TextUtils.isEmpty(iface)) {
1742 loge("Setting MTU size with null iface.");
1743 return;
1744 }
1745
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001747 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 mNetd.setMtu(iface, mtu);
1749 } catch (Exception e) {
1750 Slog.e(TAG, "exception in setMtu()" + e);
1751 }
1752 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001753
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001754 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001755 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1756
1757 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001758 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001759 protected MockableSystemProperties getSystemProperties() {
1760 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001761 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001762
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001763 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1764 if (isDefaultNetwork(nai) == false) {
1765 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001766 }
1767
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001768 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1769 String[] values = null;
1770 if (tcpBufferSizes != null) {
1771 values = tcpBufferSizes.split(",");
1772 }
1773
1774 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001775 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001776 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1777 values = tcpBufferSizes.split(",");
1778 }
1779
1780 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1781
1782 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001783 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001784
1785 final String prefix = "/sys/kernel/ipv4/tcp_";
1786 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1787 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1788 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1789 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1790 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1791 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1792 mCurrentTcpBufferSizes = tcpBufferSizes;
1793 } catch (IOException e) {
1794 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001795 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001796
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001797 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001798 Settings.Global.TCP_DEFAULT_INIT_RWND,
1799 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001800 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1801 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001802 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001803 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001804 }
1805
Mattias Falk8b47b362011-08-23 14:15:13 +02001806 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001807 /*
1808 * Tell the VMs to toss their DNS caches
1809 */
1810 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1811 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001812 /*
1813 * Connectivity events can happen before boot has completed ...
1814 */
1815 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001816 final long ident = Binder.clearCallingIdentity();
1817 try {
1818 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1819 } finally {
1820 Binder.restoreCallingIdentity(ident);
1821 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001822 }
1823
Robert Greenwalt562cc542014-05-15 18:07:26 -07001824 @Override
1825 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001826 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001827 NETWORK_RESTORE_DELAY_PROP_NAME);
1828 if(restoreDefaultNetworkDelayStr != null &&
1829 restoreDefaultNetworkDelayStr.length() != 0) {
1830 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001831 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001832 } catch (NumberFormatException e) {
1833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001835 // if the system property isn't set, use the value for the apn type
1836 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1837
1838 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1839 (mNetConfigs[networkType] != null)) {
1840 ret = mNetConfigs[networkType].restoreTime;
1841 }
1842 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001845 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001846 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001847 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001848 }
1849 return false;
1850 }
1851
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001852 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1853 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1854 final long DIAG_TIME_MS = 5000;
1855 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1856 // Start gathering diagnostic information.
1857 netDiags.add(new NetworkDiagnostics(
1858 nai.network,
1859 new LinkProperties(nai.linkProperties), // Must be a copy.
1860 DIAG_TIME_MS));
1861 }
1862
1863 for (NetworkDiagnostics netDiag : netDiags) {
1864 pw.println();
1865 netDiag.waitForMeasurements();
1866 netDiag.dump(pw);
1867 }
1868 }
1869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001871 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1872 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001873 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001874
Erik Kline7747fd42017-05-12 16:52:48 +09001875 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001876 dumpNetworkDiagnostics(pw);
1877 return;
Erik Klineee363c42017-05-29 09:11:03 +09001878 } else if (argsContain(args, TETHERING_ARG)) {
1879 mTethering.dump(fd, pw, args);
1880 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001881 }
Erik Kline379747a2015-06-05 17:47:34 +09001882
Lorenzo Colittie3805462015-06-03 11:18:24 +09001883 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001884 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001885 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001886 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001887 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001888 pw.println();
1889
Paul Jensen85cf78e2015-06-25 13:25:07 -04001890 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001891 pw.print("Active default network: ");
1892 if (defaultNai == null) {
1893 pw.println("none");
1894 } else {
1895 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001897 pw.println();
1898
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001899 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001900 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001901 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1902 pw.println(nai.toString());
1903 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001904 pw.println(String.format(
1905 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1906 nai.numForegroundNetworkRequests(),
1907 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1908 nai.numBackgroundNetworkRequests(),
1909 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001910 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001911 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1912 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001913 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001914 pw.decreaseIndent();
1915 pw.println("Lingered:");
1916 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001917 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001918 pw.decreaseIndent();
1919 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001920 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001921 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001923
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001924 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001925 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1927 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001928 }
1929 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001930 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001931
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001932 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001933
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001934 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001935 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001936
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001937 pw.println();
1938 mKeepaliveTracker.dump(pw);
1939
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001940 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001941 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942
Erik Kline7747fd42017-05-12 16:52:48 +09001943 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001944 pw.println();
1945 synchronized (mValidationLogs) {
1946 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001947 for (ValidationLog p : mValidationLogs) {
1948 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001949 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001950 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001951 pw.decreaseIndent();
1952 }
1953 }
Erik Kline7523eb32015-07-09 18:24:03 +09001954
1955 pw.println();
1956 pw.println("mNetworkRequestInfoLogs (most recent first):");
1957 pw.increaseIndent();
1958 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1959 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001960
1961 pw.println();
1962 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1963 pw.increaseIndent();
1964 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1965 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001966
1967 pw.println();
1968 pw.println("NetTransition WakeLock activity (most recent first):");
1969 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001970 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1971 pw.println("total releases: " + mTotalWakelockReleases);
1972 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1973 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1974 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1975 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1976 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1977 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001978 mWakelockLogs.reverseDump(fd, pw, args);
1979 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 }
1982
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001983 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001984 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001985 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001986 if (officialNai != null && officialNai.equals(nai)) return true;
1987 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001988 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001989 " - " + nai);
1990 }
1991 return false;
1992 }
1993
Robert Greenwalt42acef32009-08-12 16:08:25 -07001994 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001995 private class NetworkStateTrackerHandler extends Handler {
1996 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001997 super(looper);
1998 }
1999
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002000 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002002 default:
2003 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002004 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002005 handleAsyncChannelHalfConnect(msg);
2006 break;
2007 }
2008 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2009 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2010 if (nai != null) nai.asyncChannel.disconnect();
2011 break;
2012 }
2013 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2014 handleAsyncChannelDisconnected(msg);
2015 break;
2016 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 }
2018 return true;
2019 }
2020
2021 private void maybeHandleNetworkAgentMessage(Message msg) {
2022 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2023 if (nai == null) {
2024 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002025 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002026 }
2027 return;
2028 }
2029
2030 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2033 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002034 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2035 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002036 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002037 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002038 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002039 break;
2040 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002042 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 break;
2044 }
2045 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002046 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 updateNetworkInfo(nai, info);
2048 break;
2049 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002050 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002051 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002052 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002053 break;
2054 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002055 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002056 try {
2057 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002058 } catch (Exception e) {
2059 // Never crash!
2060 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002061 }
2062 break;
2063 }
2064 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002065 try {
2066 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002067 } catch (Exception e) {
2068 // Never crash!
2069 loge("Exception in removeVpnUidRanges: " + e);
2070 }
2071 break;
2072 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002073 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002074 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2075 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002076 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002077 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002078 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002079 break;
2080 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002081 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002082 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2083 break;
2084 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002085 }
2086 }
2087
2088 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2089 switch (msg.what) {
2090 default:
2091 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002092 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002093 final NetworkAgentInfo nai;
2094 synchronized (mNetworkForNetId) {
2095 nai = mNetworkForNetId.get(msg.arg2);
2096 }
2097 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002098 final boolean valid =
2099 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002100 final boolean wasValidated = nai.lastValidated;
Hugo Benichi380a0632017-10-20 09:25:29 +09002101 final boolean wasDefault = isDefaultNetwork(nai);
Paul Jensen232437312016-04-06 09:51:26 -04002102 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2103 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002104 if (valid != nai.lastValidated) {
Hugo Benichi380a0632017-10-20 09:25:29 +09002105 if (wasDefault) {
2106 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2107 SystemClock.elapsedRealtime(), valid);
2108 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04002109 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002110 nai.lastValidated = valid;
2111 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002112 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002113 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2114 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002115 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002116 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002117 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002118 Bundle redirectUrlBundle = new Bundle();
2119 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002120 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002121 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002122 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002123 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002124 if (wasValidated && !nai.lastValidated) {
2125 handleNetworkUnvalidated(nai);
2126 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 break;
2129 }
Paul Jensen869868be2014-05-15 10:33:05 -04002130 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002131 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002132 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002133 final NetworkAgentInfo nai;
2134 synchronized (mNetworkForNetId) {
2135 nai = mNetworkForNetId.get(netId);
2136 }
Calvin Onbe96da12016-10-11 15:10:46 -07002137 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002138 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002139 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002140 nai.lastCaptivePortalDetected = visible;
2141 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002142 if (nai.lastCaptivePortalDetected &&
2143 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2144 if (DBG) log("Avoiding captive portal network: " + nai.name());
2145 nai.asyncChannel.sendMessage(
2146 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2147 teardownUnneededNetwork(nai);
2148 break;
2149 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002150 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002151 }
2152 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002153 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002154 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002155 if (nai == null) {
2156 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2157 break;
2158 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002159 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002160 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002161 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002162 }
Paul Jensen869868be2014-05-15 10:33:05 -04002163 }
Paul Jensen869868be2014-05-15 10:33:05 -04002164 break;
2165 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002166 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002167 return true;
2168 }
2169
Calvin Onbe96da12016-10-11 15:10:46 -07002170 private int getCaptivePortalMode() {
2171 return Settings.Global.getInt(mContext.getContentResolver(),
2172 Settings.Global.CAPTIVE_PORTAL_MODE,
2173 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2174 }
2175
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002176 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2177 switch (msg.what) {
2178 default:
2179 return false;
2180 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2181 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2182 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2183 handleLingerComplete(nai);
2184 }
2185 break;
2186 }
2187 }
2188 return true;
2189 }
2190
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002191 @Override
2192 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002193 if (!maybeHandleAsyncChannelMessage(msg) &&
2194 !maybeHandleNetworkMonitorMessage(msg) &&
2195 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002196 maybeHandleNetworkAgentMessage(msg);
2197 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002198 }
2199 }
2200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002201 private void updateLingerState(NetworkAgentInfo nai, long now) {
2202 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2203 // 2. If the network was lingering and there are now requests, unlinger it.
2204 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2205 // one lingered request, start lingering.
2206 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002207 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002208 if (DBG) log("Unlingering " + nai.name());
2209 nai.unlinger();
2210 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002211 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002212 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002213 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002214 nai.linger();
2215 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2216 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2217 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002218 }
2219
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 private void handleAsyncChannelHalfConnect(Message msg) {
2221 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002222 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002223 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2224 if (VDBG) log("NetworkFactory connected");
2225 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002226 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002227 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002228 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002229 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002230 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002231 }
2232 } else {
2233 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002234 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002235 }
2236 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2237 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2238 if (VDBG) log("NetworkAgent connected");
2239 // A network agent has requested a connection. Establish the connection.
2240 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2241 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2242 } else {
2243 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002244 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002245 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002246 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002247 synchronized (mNetworkForNetId) {
2248 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002249 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002250 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002251 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002252 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002253 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002254 }
2255 }
2256 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002257
Robert Greenwalt7b816022014-04-18 15:25:25 -07002258 private void handleAsyncChannelDisconnected(Message msg) {
2259 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2260 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002261 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002262 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002264 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002265 // TODO - if we move the logic to the network agent (have them disconnect
2266 // because they lost all their requests or because their score isn't good)
2267 // then they would disconnect organically, report their new state and then
2268 // disconnect the channel.
2269 if (nai.networkInfo.isConnected()) {
2270 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2271 null, null);
2272 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002273 final boolean wasDefault = isDefaultNetwork(nai);
2274 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002275 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002276 // Log default network disconnection before required book-keeping.
2277 // Let rematchAllNetworksAndRequests() below record a new default network event
2278 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2279 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002280 long now = SystemClock.elapsedRealtime();
2281 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002282 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002283 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002284 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2285 // by other networks that are already connected. Perhaps that can be done by
2286 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2287 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002288 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002289 mKeepaliveTracker.handleStopAllKeepalives(nai,
2290 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002291 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2292 // Disable wakeup packet monitoring for each interface.
2293 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2294 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002295 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002296 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002297 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002298 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002299 // Remove the NetworkAgent, but don't mark the netId as
2300 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002301 mNetworkForNetId.remove(nai.network.netId);
2302 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002303 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002304 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2305 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002306 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002307 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002308 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002309 sendUpdatedScoreToFactories(request, 0);
2310 }
2311 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002312 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002313 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002315 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002316 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002318 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002319 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002320 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002321 if (nai.created) {
2322 // Tell netd to clean up the configuration for this network
2323 // (routing rules, DNS, etc).
2324 // This may be slow as it requires a lot of netd shelling out to ip and
2325 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2326 // after we've rematched networks with requests which should make a potential
2327 // fallback network the default or requested a new network from the
2328 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2329 // long time.
2330 try {
2331 mNetd.removeNetwork(nai.network.netId);
2332 } catch (Exception e) {
2333 loge("Exception removing network: " + e);
2334 }
2335 }
2336 synchronized (mNetworkForNetId) {
2337 mNetIdInUse.delete(nai.network.netId);
2338 }
2339 } else {
2340 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2341 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 }
2343 }
2344
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002345 // If this method proves to be too slow then we can maintain a separate
2346 // pendingIntent => NetworkRequestInfo map.
2347 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2348 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2349 Intent intent = pendingIntent.getIntent();
2350 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2351 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2352 if (existingPendingIntent != null &&
2353 existingPendingIntent.getIntent().filterEquals(intent)) {
2354 return entry.getValue();
2355 }
2356 }
2357 return null;
2358 }
2359
2360 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2361 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2362
2363 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2364 if (existingRequest != null) { // remove the existing request.
2365 if (DBG) log("Replacing " + existingRequest.request + " with "
2366 + nri.request + " because their intents matched.");
2367 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2368 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002369 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002370 }
2371
Erik Klineda4bfa82015-04-30 12:58:40 +09002372 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002373 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002374 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002375 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002376 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002377 if (nri.request.networkCapabilities.hasSignalStrength() &&
2378 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2379 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002380 }
2381 }
2382 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002383 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002384 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002385 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002386 }
2387 }
2388
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002389 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2390 int callingUid) {
2391 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2392 if (nri != null) {
2393 handleReleaseNetworkRequest(nri.request, callingUid);
2394 }
2395 }
2396
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002397 // Determines whether the network is the best (or could become the best, if it validated), for
2398 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2399 // on the value of reason:
2400 //
2401 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2402 // then it should be torn down.
2403 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2404 // then it should be lingered.
2405 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2406 final int numRequests;
2407 switch (reason) {
2408 case TEARDOWN:
2409 numRequests = nai.numRequestNetworkRequests();
2410 break;
2411 case LINGER:
2412 numRequests = nai.numForegroundNetworkRequests();
2413 break;
2414 default:
2415 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2416 return true;
2417 }
2418
2419 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002420 return false;
2421 }
Paul Jensene0988542015-06-25 15:30:08 -04002422 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002423 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2424 // Background requests don't affect lingering.
2425 continue;
2426 }
2427
Paul Jensene0988542015-06-25 15:30:08 -04002428 // If this Network is already the highest scoring Network for a request, or if
2429 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002430 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002431 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002432 // Note that this catches two important cases:
2433 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2434 // is currently satisfying the request. This is desirable when
2435 // cellular ends up validating but WiFi does not.
2436 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002437 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002438 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002439 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002440 nai.getCurrentScoreAsValidated())) {
2441 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002442 }
2443 }
Paul Jensene0988542015-06-25 15:30:08 -04002444 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002445 }
2446
Erik Klineacdd6392016-07-07 16:50:58 +09002447 private NetworkRequestInfo getNriForAppRequest(
2448 NetworkRequest request, int callingUid, String requestedOperation) {
2449 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2450
Robert Greenwalt9258c642014-03-26 16:47:06 -07002451 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002452 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002453 log(String.format("UID %d attempted to %s for unowned request %s",
2454 callingUid, requestedOperation, nri));
2455 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002456 }
Erik Klineacdd6392016-07-07 16:50:58 +09002457 }
2458
2459 return nri;
2460 }
2461
Erik Kline57faba92015-11-25 12:49:38 +09002462 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002463 if (mNetworkRequests.get(nri.request) == null) {
2464 return;
Erik Kline57faba92015-11-25 12:49:38 +09002465 }
Hugo Benichicd952782017-09-20 11:20:14 +09002466 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002467 return;
2468 }
2469 if (VDBG || (DBG && nri.request.isRequest())) {
2470 log("releasing " + nri.request + " (timeout)");
2471 }
2472 handleRemoveNetworkRequest(nri);
2473 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002474 }
2475
Erik Klineacdd6392016-07-07 16:50:58 +09002476 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002477 final NetworkRequestInfo nri =
2478 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2479 if (nri == null) {
2480 return;
Erik Kline57faba92015-11-25 12:49:38 +09002481 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002482 if (VDBG || (DBG && nri.request.isRequest())) {
2483 log("releasing " + nri.request + " (release request)");
2484 }
2485 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002486 }
Erik Klineacdd6392016-07-07 16:50:58 +09002487
Hugo Benichidba33db2017-03-23 22:40:44 +09002488 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002489 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002490 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002491 synchronized (mUidToNetworkRequestCount) {
2492 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2493 if (requests < 1) {
2494 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2495 nri.mUid);
2496 } else if (requests == 1) {
2497 mUidToNetworkRequestCount.removeAt(
2498 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2499 } else {
2500 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2501 }
2502 }
2503 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2504 if (nri.request.isRequest()) {
2505 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002506 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002507 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002508 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002509 nai.removeRequest(nri.request.requestId);
2510 if (VDBG) {
2511 log(" Removing from current network " + nai.name() +
2512 ", leaving " + nai.numNetworkRequests() + " requests.");
2513 }
2514 // If there are still lingered requests on this network, don't tear it down,
2515 // but resume lingering instead.
2516 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002517 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002518 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2519 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002520 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002521 wasKept = true;
2522 }
Hugo Benichicd952782017-09-20 11:20:14 +09002523 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002524 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2525 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002526 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002527 }
Erik Klineacdd6392016-07-07 16:50:58 +09002528 }
2529
2530 // TODO: remove this code once we know that the Slog.wtf is never hit.
2531 //
2532 // Find all networks that are satisfying this request and remove the request
2533 // from their request lists.
2534 // TODO - it's my understanding that for a request there is only a single
2535 // network satisfying it, so this loop is wasteful
2536 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2537 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2538 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2539 otherNai.name() + ", but mNetworkAgentInfos says " +
2540 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002541 }
2542 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002543
Erik Klineacdd6392016-07-07 16:50:58 +09002544 // Maintain the illusion. When this request arrived, we might have pretended
2545 // that a network connected to serve it, even though the network was already
2546 // connected. Now that this request has gone away, we might have to pretend
2547 // that the network disconnected. LegacyTypeTracker will generate that
2548 // phantom disconnect for this type.
2549 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2550 boolean doRemove = true;
2551 if (wasKept) {
2552 // check if any of the remaining requests for this network are for the
2553 // same legacy type - if so, don't remove the nai
2554 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2555 NetworkRequest otherRequest = nai.requestAt(i);
2556 if (otherRequest.legacyType == nri.request.legacyType &&
2557 otherRequest.isRequest()) {
2558 if (DBG) log(" still have other legacy request - leaving");
2559 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002560 }
2561 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002562 }
2563
Erik Klineacdd6392016-07-07 16:50:58 +09002564 if (doRemove) {
2565 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 }
2567 }
Erik Klineacdd6392016-07-07 16:50:58 +09002568
2569 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2570 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2571 nri.request);
2572 }
2573 } else {
2574 // listens don't have a singular affectedNetwork. Check all networks to see
2575 // if this listen request applies and remove it.
2576 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2577 nai.removeRequest(nri.request.requestId);
2578 if (nri.request.networkCapabilities.hasSignalStrength() &&
2579 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2580 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2581 }
2582 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002583 }
2584 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002585
Lorenzo Colitti18660282016-07-04 12:55:44 +09002586 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002587 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2588 enforceConnectivityInternalPermission();
2589 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002590 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002591 }
2592
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002593 @Override
2594 public void setAvoidUnvalidated(Network network) {
2595 enforceConnectivityInternalPermission();
2596 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2597 }
2598
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002599 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2600 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2601 " accept=" + accept + " always=" + always);
2602
2603 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2604 if (nai == null) {
2605 // Nothing to do.
2606 return;
2607 }
2608
2609 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002610 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002611 return;
2612 }
2613
2614 if (!nai.networkMisc.explicitlySelected) {
2615 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2616 }
2617
2618 if (accept != nai.networkMisc.acceptUnvalidated) {
2619 int oldScore = nai.getCurrentScore();
2620 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002621 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002622 sendUpdatedScoreToFactories(nai);
2623 }
2624
2625 if (always) {
2626 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002627 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002628 }
2629
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002630 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002631 // Tell the NetworkAgent to not automatically reconnect to the network.
2632 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2633 // Teardown the nework.
2634 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002635 }
2636
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002637 }
2638
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002639 private void handleSetAvoidUnvalidated(Network network) {
2640 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2641 if (nai == null || nai.lastValidated) {
2642 // Nothing to do. The network either disconnected or revalidated.
2643 return;
2644 }
2645 if (!nai.avoidUnvalidated) {
2646 int oldScore = nai.getCurrentScore();
2647 nai.avoidUnvalidated = true;
2648 rematchAllNetworksAndRequests(nai, oldScore);
2649 sendUpdatedScoreToFactories(nai);
2650 }
2651 }
2652
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002653 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002654 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002655 mHandler.sendMessageDelayed(
2656 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2657 PROMPT_UNVALIDATED_DELAY_MS);
2658 }
2659
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002660 @Override
2661 public void startCaptivePortalApp(Network network) {
2662 enforceConnectivityInternalPermission();
2663 mHandler.post(() -> {
2664 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2665 if (nai == null) return;
2666 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2667 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2668 });
2669 }
2670
Hugo Benichic8e9e122016-09-14 23:23:08 +00002671 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002672 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002673 }
2674
Erik Kline065ab6e2016-10-02 18:02:14 +09002675 private void rematchForAvoidBadWifiUpdate() {
2676 rematchAllNetworksAndRequests(null, 0);
2677 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2678 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2679 sendUpdatedScoreToFactories(nai);
2680 }
2681 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002682 }
2683
Erik Kline065ab6e2016-10-02 18:02:14 +09002684 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002685 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002686 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002687 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002688 if (!configRestrict) {
2689 pw.println("Bad Wi-Fi avoidance: unrestricted");
2690 return;
2691 }
2692
2693 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2694 pw.increaseIndent();
2695 pw.println("Config restrict: " + configRestrict);
2696
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002697 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002698 String description;
2699 // Can't use a switch statement because strings are legal case labels, but null is not.
2700 if ("0".equals(value)) {
2701 description = "get stuck";
2702 } else if (value == null) {
2703 description = "prompt";
2704 } else if ("1".equals(value)) {
2705 description = "avoid";
2706 } else {
2707 description = value + " (?)";
2708 }
2709 pw.println("User setting: " + description);
2710 pw.println("Network overrides:");
2711 pw.increaseIndent();
2712 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2713 if (nai.avoidUnvalidated) {
2714 pw.println(nai.name());
2715 }
2716 }
2717 pw.decreaseIndent();
2718 pw.decreaseIndent();
2719 }
2720
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002721 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2722 final String action;
2723 switch (type) {
2724 case NO_INTERNET:
2725 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2726 break;
2727 case LOST_INTERNET:
2728 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2729 break;
2730 default:
2731 Slog.wtf(TAG, "Unknown notification type " + type);
2732 return;
2733 }
2734
2735 Intent intent = new Intent(action);
2736 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2737 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2738 intent.setClassName("com.android.settings",
2739 "com.android.settings.wifi.WifiNoInternetDialog");
2740
2741 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2742 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2743 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2744 }
2745
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002747 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002748 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2749
2750 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2751 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002752 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002753 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002754 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2755 return;
2756 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002757 showValidationNotification(nai, NotificationType.NO_INTERNET);
2758 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002759
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002760 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2761 NetworkCapabilities nc = nai.networkCapabilities;
2762 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002763
Erik Kline065ab6e2016-10-02 18:02:14 +09002764 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002765 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002766 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2767 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 }
2769
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002770 @Override
2771 public int getMultipathPreference(Network network) {
2772 enforceAccessPermission();
2773
2774 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002775 if (nai != null && nai.networkCapabilities
2776 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002777 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2778 }
2779
2780 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2781 }
2782
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002783 private class InternalHandler extends Handler {
2784 public InternalHandler(Looper looper) {
2785 super(looper);
2786 }
2787
2788 @Override
2789 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002790 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002791 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002792 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002793 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002794 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002795 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002796 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002797 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002798 break;
2799 }
Jason Monkdecd2952013-10-10 14:02:51 -04002800 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002801 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002802 break;
2803 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002804 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002805 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2806 break;
2807 }
2808 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2809 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002810 break;
2811 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002812 case EVENT_REGISTER_NETWORK_AGENT: {
2813 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2814 break;
2815 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002816 case EVENT_REGISTER_NETWORK_REQUEST:
2817 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002818 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002819 break;
2820 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002821 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2822 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002823 handleRegisterNetworkRequestWithIntent(msg);
2824 break;
2825 }
Erik Kline57faba92015-11-25 12:49:38 +09002826 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2827 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2828 handleTimedOutNetworkRequest(nri);
2829 break;
2830 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002831 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2832 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2833 break;
2834 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002835 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002836 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002837 break;
2838 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002839 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002840 Network network = (Network) msg.obj;
2841 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002842 break;
2843 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002844 case EVENT_SET_AVOID_UNVALIDATED: {
2845 handleSetAvoidUnvalidated((Network) msg.obj);
2846 break;
2847 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002848 case EVENT_PROMPT_UNVALIDATED: {
2849 handlePromptUnvalidated((Network) msg.obj);
2850 break;
2851 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002852 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2853 handleMobileDataAlwaysOn();
2854 break;
2855 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002856 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2857 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2858 mKeepaliveTracker.handleStartKeepalive(msg);
2859 break;
2860 }
2861 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2862 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2863 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2864 int slot = msg.arg1;
2865 int reason = msg.arg2;
2866 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2867 break;
2868 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002869 case EVENT_SYSTEM_READY: {
2870 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2871 nai.networkMonitor.systemReady = true;
2872 }
2873 break;
2874 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002875 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002876 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002877 break;
2878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 }
2880 }
2881 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002882
2883 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002884 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002885 public int tether(String iface, String callerPkg) {
2886 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002887 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002888 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002889 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002890 } else {
2891 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2892 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002893 }
2894
2895 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002896 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002897 public int untether(String iface, String callerPkg) {
2898 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002899
2900 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002901 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002902 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002903 } else {
2904 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2905 }
2906 }
2907
2908 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002909 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002910 public int getLastTetherError(String iface) {
2911 enforceTetherAccessPermission();
2912
2913 if (isTetheringSupported()) {
2914 return mTethering.getLastTetherError(iface);
2915 } else {
2916 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2917 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002918 }
2919
2920 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002921 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002922 public String[] getTetherableUsbRegexs() {
2923 enforceTetherAccessPermission();
2924 if (isTetheringSupported()) {
2925 return mTethering.getTetherableUsbRegexs();
2926 } else {
2927 return new String[0];
2928 }
2929 }
2930
Lorenzo Colitti18660282016-07-04 12:55:44 +09002931 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002932 public String[] getTetherableWifiRegexs() {
2933 enforceTetherAccessPermission();
2934 if (isTetheringSupported()) {
2935 return mTethering.getTetherableWifiRegexs();
2936 } else {
2937 return new String[0];
2938 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002939 }
2940
Lorenzo Colitti18660282016-07-04 12:55:44 +09002941 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002942 public String[] getTetherableBluetoothRegexs() {
2943 enforceTetherAccessPermission();
2944 if (isTetheringSupported()) {
2945 return mTethering.getTetherableBluetoothRegexs();
2946 } else {
2947 return new String[0];
2948 }
2949 }
2950
Lorenzo Colitti18660282016-07-04 12:55:44 +09002951 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002952 public int setUsbTethering(boolean enable, String callerPkg) {
2953 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002954 if (isTetheringSupported()) {
2955 return mTethering.setUsbTethering(enable);
2956 } else {
2957 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2958 }
2959 }
2960
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002961 // TODO - move iface listing, queries, etc to new module
2962 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002963 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002964 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002965 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002966 return mTethering.getTetherableIfaces();
2967 }
2968
Lorenzo Colitti18660282016-07-04 12:55:44 +09002969 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002970 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002971 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002972 return mTethering.getTetheredIfaces();
2973 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002974
Lorenzo Colitti18660282016-07-04 12:55:44 +09002975 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002976 public String[] getTetheringErroredIfaces() {
2977 enforceTetherAccessPermission();
2978 return mTethering.getErroredIfaces();
2979 }
2980
Lorenzo Colitti18660282016-07-04 12:55:44 +09002981 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002982 public String[] getTetheredDhcpRanges() {
2983 enforceConnectivityInternalPermission();
2984 return mTethering.getTetheredDhcpRanges();
2985 }
2986
Udam Sainic3b640c2017-06-07 12:06:28 -07002987 @Override
2988 public boolean isTetheringSupported(String callerPkg) {
2989 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
2990 return isTetheringSupported();
2991 }
2992
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002993 // if ro.tether.denied = true we default to no tethering
2994 // gservices could set the secure setting to 1 though to enable it on a build where it
2995 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07002996 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002997 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2998 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2999 Settings.Global.TETHER_SUPPORTED, defaultVal));
3000 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003001 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003002
3003 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3004 boolean adminUser = false;
3005 final long token = Binder.clearCallingIdentity();
3006 try {
3007 adminUser = mUserManager.isAdminUser();
3008 } finally {
3009 Binder.restoreCallingIdentity(token);
3010 }
3011
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003012 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003013 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003014
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003015 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003016 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3017 String callerPkg) {
3018 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003019 if (!isTetheringSupported()) {
3020 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3021 return;
3022 }
3023 mTethering.startTethering(type, receiver, showProvisioningUi);
3024 }
3025
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003026 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003027 public void stopTethering(int type, String callerPkg) {
3028 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003029 mTethering.stopTethering(type);
3030 }
3031
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003032 // Called when we lose the default network and have no replacement yet.
3033 // This will automatically be cleared after X seconds or a new default network
3034 // becomes CONNECTED, whichever happens first. The timer is started by the
3035 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003036 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003037 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003038 if (mNetTransitionWakeLock.isHeld()) {
3039 return;
3040 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003041 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003042 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3043 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003044 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003045 mWakelockLogs.log("ACQUIRE for " + forWhom);
3046 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3047 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003048 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003049
Hugo Benichi4c31b342017-03-30 23:18:10 +09003050 // Called when we gain a new default network to release the network transition wakelock in a
3051 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3052 // message is cancelled.
3053 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003054 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003055 if (!mNetTransitionWakeLock.isHeld()) {
3056 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003057 }
3058 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003059 // Cancel self timeout on wakelock hold.
3060 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3061 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3062 mHandler.sendMessageDelayed(msg, 1000);
3063 }
3064
3065 // Called when either message of ensureNetworkTransitionWakelock or
3066 // scheduleReleaseNetworkTransitionWakelock is processed.
3067 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3068 String event = eventName(eventId);
3069 synchronized (this) {
3070 if (!mNetTransitionWakeLock.isHeld()) {
3071 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3072 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3073 return;
3074 }
3075 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003076 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3077 mTotalWakelockDurationMs += lockDuration;
3078 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3079 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003080 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003081 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003082 }
3083
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003084 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003085 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003086 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003087 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003088 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003089 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003090 }
3091
Lorenzo Colitti18660282016-07-04 12:55:44 +09003092 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003093 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003094 enforceAccessPermission();
3095 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003096 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003097 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003098 mHandler.sendMessage(
3099 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3100 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003101
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003102 private void handleReportNetworkConnectivity(
3103 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003104 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003105 if (network == null) {
3106 nai = getDefaultNetwork();
3107 } else {
3108 nai = getNetworkAgentInfoForNetwork(network);
3109 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003110 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3111 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3112 return;
3113 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003114 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003115 if (hasConnectivity == nai.lastValidated) {
3116 return;
3117 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003118 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003119 int netid = nai.network.netId;
3120 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003121 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003122 // Validating a network that has not yet connected could result in a call to
3123 // rematchNetworkAndRequests() which is not meant to work on such networks.
3124 if (!nai.everConnected) {
3125 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003126 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003127 LinkProperties lp = getLinkProperties(nai);
3128 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3129 return;
3130 }
3131 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003132 }
3133
Paul Jensencee9b512015-05-06 07:32:40 -04003134 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003135 // this information is already available as a world read/writable jvm property
3136 // so this API change wouldn't have a benifit. It also breaks the passing
3137 // of proxy info to all the JVMs.
3138 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003139 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003140 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003141 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3142 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003143 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003144 }
3145
Lorenzo Colitti18660282016-07-04 12:55:44 +09003146 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003147 public ProxyInfo getProxyForNetwork(Network network) {
3148 if (network == null) return getDefaultProxy();
3149 final ProxyInfo globalProxy = getGlobalProxy();
3150 if (globalProxy != null) return globalProxy;
3151 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3152 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3153 // caller may not have.
3154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3155 if (nai == null) return null;
3156 synchronized (nai) {
3157 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3158 if (proxyInfo == null) return null;
3159 return new ProxyInfo(proxyInfo);
3160 }
3161 }
3162
Paul Jensene0bef712014-12-10 15:12:18 -05003163 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3164 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3165 // proxy is null then there is no proxy in place).
3166 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3167 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3168 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3169 proxy = null;
3170 }
3171 return proxy;
3172 }
3173
3174 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3175 // better for determining if a new proxy broadcast is necessary:
3176 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3177 // avoid unnecessary broadcasts.
3178 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3179 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3180 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3181 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3182 // all set.
3183 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3184 a = canonicalizeProxyInfo(a);
3185 b = canonicalizeProxyInfo(b);
3186 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3187 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3188 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3189 }
3190
Jason Monk207900c2014-04-25 15:00:09 -04003191 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003192 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003193
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003194 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003195 if (proxyProperties == mGlobalProxy) return;
3196 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3197 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3198
3199 String host = "";
3200 int port = 0;
3201 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003202 String pacFileUrl = "";
3203 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003204 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003205 if (!proxyProperties.isValid()) {
3206 if (DBG)
3207 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3208 return;
3209 }
Jason Monk207900c2014-04-25 15:00:09 -04003210 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003211 host = mGlobalProxy.getHost();
3212 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003213 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003214 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003215 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003216 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003217 } else {
3218 mGlobalProxy = null;
3219 }
3220 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003221 final long token = Binder.clearCallingIdentity();
3222 try {
3223 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3224 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3225 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3226 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003227 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003228 } finally {
3229 Binder.restoreCallingIdentity(token);
3230 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003231
Jason Monkcf0f97a2014-10-02 15:39:38 -04003232 if (mGlobalProxy == null) {
3233 proxyProperties = mDefaultProxy;
3234 }
3235 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003236 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003237 }
3238
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003239 private void loadGlobalProxy() {
3240 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003241 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3242 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3243 String exclList = Settings.Global.getString(res,
3244 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003245 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3246 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003247 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003248 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003249 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003250 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003251 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003252 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003253 if (!proxyProperties.isValid()) {
3254 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3255 return;
3256 }
3257
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003258 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003259 mGlobalProxy = proxyProperties;
3260 }
3261 }
3262 }
3263
Jason Monk207900c2014-04-25 15:00:09 -04003264 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003265 // this information is already available as a world read/writable jvm property
3266 // so this API change wouldn't have a benifit. It also breaks the passing
3267 // of proxy info to all the JVMs.
3268 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003269 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003270 return mGlobalProxy;
3271 }
3272 }
3273
Jason Monk207900c2014-04-25 15:00:09 -04003274 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003275 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003276 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003277 proxy = null;
3278 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003279 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003281 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003282 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003283 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3284 return;
3285 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003286
3287 // This call could be coming from the PacManager, containing the port of the local
3288 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3289 // global (to get the correct local port), and send a broadcast.
3290 // TODO: Switch PacManager to have its own message to send back rather than
3291 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003292 if ((mGlobalProxy != null) && (proxy != null)
3293 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003294 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3295 mGlobalProxy = proxy;
3296 sendProxyBroadcast(mGlobalProxy);
3297 return;
3298 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003299 mDefaultProxy = proxy;
3300
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003301 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003302 if (!mDefaultProxyDisabled) {
3303 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003304 }
3305 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306 }
3307
Paul Jensene0bef712014-12-10 15:12:18 -05003308 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3309 // This method gets called when any network changes proxy, but the broadcast only ever contains
3310 // the default proxy (even if it hasn't changed).
3311 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3312 // world where an app might be bound to a non-default network.
3313 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3314 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3315 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3316
3317 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3318 sendProxyBroadcast(getDefaultProxy());
3319 }
3320 }
3321
Robert Greenwalt434203a2010-10-11 16:00:27 -07003322 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003323 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3324 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325 if (!TextUtils.isEmpty(proxy)) {
3326 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003327 if (data.length == 0) {
3328 return;
3329 }
3330
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 String proxyHost = data[0];
3332 int proxyPort = 8080;
3333 if (data.length > 1) {
3334 try {
3335 proxyPort = Integer.parseInt(data[1]);
3336 } catch (NumberFormatException e) {
3337 return;
3338 }
3339 }
Jason Monk207900c2014-04-25 15:00:09 -04003340 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 setGlobalProxy(p);
3342 }
3343 }
3344
Jason Monk207900c2014-04-25 15:00:09 -04003345 private void sendProxyBroadcast(ProxyInfo proxy) {
3346 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003347 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003348 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003350 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3351 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003352 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003353 final long ident = Binder.clearCallingIdentity();
3354 try {
3355 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3356 } finally {
3357 Binder.restoreCallingIdentity(ident);
3358 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 }
3360
3361 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003362 final private HashMap<Uri, Integer> mUriEventMap;
3363 final private Context mContext;
3364 final private Handler mHandler;
3365
3366 SettingsObserver(Context context, Handler handler) {
3367 super(null);
3368 mUriEventMap = new HashMap<Uri, Integer>();
3369 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003370 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003371 }
3372
Erik Klineda4bfa82015-04-30 12:58:40 +09003373 void observe(Uri uri, int what) {
3374 mUriEventMap.put(uri, what);
3375 final ContentResolver resolver = mContext.getContentResolver();
3376 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003377 }
3378
3379 @Override
3380 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003381 Slog.wtf(TAG, "Should never be reached.");
3382 }
3383
3384 @Override
3385 public void onChange(boolean selfChange, Uri uri) {
3386 final Integer what = mUriEventMap.get(uri);
3387 if (what != null) {
3388 mHandler.obtainMessage(what.intValue()).sendToTarget();
3389 } else {
3390 loge("No matching event to send for URI=" + uri);
3391 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 }
3393 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003394
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003395 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003396 Slog.d(TAG, s);
3397 }
3398
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003399 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003400 Slog.e(TAG, s);
3401 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003402
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003403 private static void loge(String s, Throwable t) {
3404 Slog.e(TAG, s, t);
3405 }
3406
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003407 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003408 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003409 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3410 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3411 *
3412 * @param oldPackage Package name of the application which currently controls VPN, which will
3413 * be replaced. If there is no such application, this should should either be
3414 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3415 * @param newPackage Package name of the application which should gain control of VPN, or
3416 * {@code null} to disable.
3417 * @param userId User for whom to prepare the new VPN.
3418 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003419 * @hide
3420 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003421 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003422 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3423 int userId) {
3424 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003425 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003426
Hugo Benichi20035e02017-04-26 14:53:28 +09003427 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003428 Vpn vpn = mVpns.get(userId);
3429 if (vpn != null) {
3430 return vpn.prepare(oldPackage, newPackage);
3431 } else {
3432 return false;
3433 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003434 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003435 }
3436
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003437 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003438 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3439 * This method is used by system-privileged apps.
3440 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3441 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3442 *
3443 * @param packageName The package for which authorization state should change.
3444 * @param userId User for whom {@code packageName} is installed.
3445 * @param authorized {@code true} if this app should be able to start a VPN connection without
3446 * explicit user approval, {@code false} if not.
3447 *
Jeff Davidson05542602014-08-11 14:07:27 -07003448 * @hide
3449 */
3450 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003451 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3452 enforceCrossUserPermission(userId);
3453
Hugo Benichi20035e02017-04-26 14:53:28 +09003454 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003455 Vpn vpn = mVpns.get(userId);
3456 if (vpn != null) {
3457 vpn.setPackageAuthorization(packageName, authorized);
3458 }
Jeff Davidson05542602014-08-11 14:07:27 -07003459 }
3460 }
3461
3462 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003463 * Configure a TUN interface and return its file descriptor. Parameters
3464 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003465 * and not available in ConnectivityManager. Permissions are checked in
3466 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003467 * @hide
3468 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003469 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003470 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003471 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003472 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003473 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003474 return mVpns.get(user).establish(config);
3475 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003476 }
3477
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003478 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003479 * Start legacy VPN, controlling native daemons as needed. Creates a
3480 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003481 */
3482 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003483 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003484 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003485 final LinkProperties egress = getActiveLinkProperties();
3486 if (egress == null) {
3487 throw new IllegalStateException("Missing active network connection");
3488 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003489 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003490 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003491 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3492 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003493 }
3494
3495 /**
3496 * Return the information of the ongoing legacy VPN. This method is used
3497 * by VpnSettings and not available in ConnectivityManager. Permissions
3498 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003499 */
3500 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003501 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3502 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003503
Hugo Benichi20035e02017-04-26 14:53:28 +09003504 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003505 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003506 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003507 }
3508
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003509 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003510 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3511 * and not available in ConnectivityManager.
3512 */
3513 @Override
3514 public VpnInfo[] getAllVpnInfo() {
3515 enforceConnectivityInternalPermission();
3516 if (mLockdownEnabled) {
3517 return new VpnInfo[0];
3518 }
3519
Hugo Benichi20035e02017-04-26 14:53:28 +09003520 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003521 List<VpnInfo> infoList = new ArrayList<>();
3522 for (int i = 0; i < mVpns.size(); i++) {
3523 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3524 if (info != null) {
3525 infoList.add(info);
3526 }
3527 }
3528 return infoList.toArray(new VpnInfo[infoList.size()]);
3529 }
3530 }
3531
3532 /**
3533 * @return VPN information for accounting, or null if we can't retrieve all required
3534 * information, e.g primary underlying iface.
3535 */
3536 @Nullable
3537 private VpnInfo createVpnInfo(Vpn vpn) {
3538 VpnInfo info = vpn.getVpnInfo();
3539 if (info == null) {
3540 return null;
3541 }
3542 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3543 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3544 // the underlyingNetworks list.
3545 if (underlyingNetworks == null) {
3546 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3547 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3548 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3549 }
3550 } else if (underlyingNetworks.length > 0) {
3551 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3552 if (linkProperties != null) {
3553 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3554 }
3555 }
3556 return info.primaryUnderlyingIface == null ? null : info;
3557 }
3558
3559 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003560 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3561 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003562 * Permissions are checked in Vpn class.
3563 * @hide
3564 */
3565 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003566 public VpnConfig getVpnConfig(int userId) {
3567 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003568 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003569 Vpn vpn = mVpns.get(userId);
3570 if (vpn != null) {
3571 return vpn.getVpnConfig();
3572 } else {
3573 return null;
3574 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003575 }
3576 }
3577
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003578 @Override
3579 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003580 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3581 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3582 return false;
3583 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003584
3585 // Tear down existing lockdown if profile was removed
3586 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3587 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003588 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3589 if (profileTag == null) {
3590 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3591 return false;
3592 }
3593 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003594 final VpnProfile profile = VpnProfile.decode(
3595 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003596 if (profile == null) {
3597 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3598 setLockdownTracker(null);
3599 return true;
3600 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003601 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003602 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003603 Vpn vpn = mVpns.get(user);
3604 if (vpn == null) {
3605 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3606 return false;
3607 }
3608 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003609 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003610 } else {
3611 setLockdownTracker(null);
3612 }
3613
3614 return true;
3615 }
3616
3617 /**
3618 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3619 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3620 */
3621 private void setLockdownTracker(LockdownVpnTracker tracker) {
3622 // Shutdown any existing tracker
3623 final LockdownVpnTracker existing = mLockdownTracker;
3624 mLockdownTracker = null;
3625 if (existing != null) {
3626 existing.shutdown();
3627 }
3628
Robin Leec3736bc2017-03-10 16:19:54 +00003629 if (tracker != null) {
3630 mLockdownTracker = tracker;
3631 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003632 }
3633 }
3634
3635 private void throwIfLockdownEnabled() {
3636 if (mLockdownEnabled) {
3637 throw new IllegalStateException("Unavailable in lockdown mode");
3638 }
3639 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003640
Robin Lee244ce8e2016-01-05 18:03:46 +00003641 /**
Robin Lee17e61832016-05-09 13:46:28 +01003642 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3643 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003644 *
Robin Lee17e61832016-05-09 13:46:28 +01003645 * @return {@code true} if the service was started, the service was already connected, or there
3646 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003647 */
Robin Lee17e61832016-05-09 13:46:28 +01003648 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003649 synchronized (mVpns) {
3650 Vpn vpn = mVpns.get(userId);
3651 if (vpn == null) {
3652 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3653 // exists already.
3654 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3655 return false;
3656 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003657
Robin Lee812800c2016-05-13 15:38:08 +01003658 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003659 }
3660 }
3661
3662 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003663 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3664 enforceSettingsPermission();
3665 enforceCrossUserPermission(userId);
3666
3667 synchronized (mVpns) {
3668 Vpn vpn = mVpns.get(userId);
3669 if (vpn == null) {
3670 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3671 return false;
3672 }
3673 return vpn.isAlwaysOnPackageSupported(packageName);
3674 }
3675 }
3676
3677 @Override
Robin Leedc679712016-05-03 13:23:03 +01003678 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003679 enforceConnectivityInternalPermission();
3680 enforceCrossUserPermission(userId);
3681
3682 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3683 if (LockdownVpnTracker.isEnabled()) {
3684 return false;
3685 }
3686
Robin Lee244ce8e2016-01-05 18:03:46 +00003687 synchronized (mVpns) {
3688 Vpn vpn = mVpns.get(userId);
3689 if (vpn == null) {
3690 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3691 return false;
3692 }
Robin Lee17e61832016-05-09 13:46:28 +01003693 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003694 return false;
3695 }
Robin Lee17e61832016-05-09 13:46:28 +01003696 if (!startAlwaysOnVpn(userId)) {
3697 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003698 return false;
3699 }
3700 }
3701 return true;
3702 }
3703
3704 @Override
3705 public String getAlwaysOnVpnPackage(int userId) {
3706 enforceConnectivityInternalPermission();
3707 enforceCrossUserPermission(userId);
3708
3709 synchronized (mVpns) {
3710 Vpn vpn = mVpns.get(userId);
3711 if (vpn == null) {
3712 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3713 return null;
3714 }
3715 return vpn.getAlwaysOnPackage();
3716 }
3717 }
3718
Wink Savilleab9321d2013-06-29 21:10:57 -07003719 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003720 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003721 // TODO: Remove? Any reason to trigger a provisioning check?
3722 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003723 }
3724
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003725 /** Location to an updatable file listing carrier provisioning urls.
3726 * An example:
3727 *
3728 * <?xml version="1.0" encoding="utf-8"?>
3729 * <provisioningUrls>
3730 * <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 -07003731 * </provisioningUrls>
3732 */
3733 private static final String PROVISIONING_URL_PATH =
3734 "/data/misc/radio/provisioning_urls.xml";
3735 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003736
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003737 /** XML tag for root element. */
3738 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3739 /** XML tag for individual url */
3740 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003741 /** XML attribute for mcc */
3742 private static final String ATTR_MCC = "mcc";
3743 /** XML attribute for mnc */
3744 private static final String ATTR_MNC = "mnc";
3745
Paul Jensen434dde82015-06-11 09:43:30 -04003746 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003747 FileReader fileReader = null;
3748 XmlPullParser parser = null;
3749 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003750
3751 try {
3752 fileReader = new FileReader(mProvisioningUrlFile);
3753 parser = Xml.newPullParser();
3754 parser.setInput(fileReader);
3755 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3756
3757 while (true) {
3758 XmlUtils.nextElement(parser);
3759
3760 String element = parser.getName();
3761 if (element == null) break;
3762
Paul Jensen434dde82015-06-11 09:43:30 -04003763 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003764 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3765 try {
3766 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3767 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3768 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3769 parser.next();
3770 if (parser.getEventType() == XmlPullParser.TEXT) {
3771 return parser.getText();
3772 }
3773 }
3774 }
3775 } catch (NumberFormatException e) {
3776 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3777 }
3778 }
3779 }
3780 return null;
3781 } catch (FileNotFoundException e) {
3782 loge("Carrier Provisioning Urls file not found");
3783 } catch (XmlPullParserException e) {
3784 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3785 } catch (IOException e) {
3786 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3787 } finally {
3788 if (fileReader != null) {
3789 try {
3790 fileReader.close();
3791 } catch (IOException e) {}
3792 }
3793 }
3794 return null;
3795 }
3796
Wink Saville42d4f082013-07-20 20:31:59 -07003797 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003798 public String getMobileProvisioningUrl() {
3799 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003800 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003801 if (TextUtils.isEmpty(url)) {
3802 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003803 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003804 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003805 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003806 }
Wink Saville8cf35602013-07-10 23:00:07 -07003807 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003808 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003809 String phoneNumber = mTelephonyManager.getLine1Number();
3810 if (TextUtils.isEmpty(phoneNumber)) {
3811 phoneNumber = "0000000000";
3812 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003813 url = String.format(url,
3814 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3815 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003816 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003817 }
3818
Wink Savilleab9321d2013-06-29 21:10:57 -07003819 return url;
3820 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003821
Wink Saville948282b2013-08-29 08:55:16 -07003822 @Override
3823 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003824 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003825 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003826 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3827 return;
3828 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003829 final long ident = Binder.clearCallingIdentity();
3830 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003831 // Concatenate the range of types onto the range of NetIDs.
3832 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3833 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003834 } finally {
3835 Binder.restoreCallingIdentity(ident);
3836 }
Wink Saville948282b2013-08-29 08:55:16 -07003837 }
Wink Saville7788c612013-08-29 14:57:08 -07003838
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003839 @Override
3840 public void setAirplaneMode(boolean enable) {
3841 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003842 final long ident = Binder.clearCallingIdentity();
3843 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003844 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003845 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003846 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3847 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003848 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003849 } finally {
3850 Binder.restoreCallingIdentity(ident);
3851 }
3852 }
3853
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003854 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003855 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003856 Vpn userVpn = mVpns.get(userId);
3857 if (userVpn != null) {
3858 loge("Starting user already has a VPN");
3859 return;
3860 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003861 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003862 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003863 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003864 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3865 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003866 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003867 }
3868
3869 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003870 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003871 Vpn userVpn = mVpns.get(userId);
3872 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003873 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003874 return;
3875 }
Robin Lee17e61832016-05-09 13:46:28 +01003876 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 mVpns.delete(userId);
3878 }
3879 }
3880
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003881 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003882 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003883 final int vpnsSize = mVpns.size();
3884 for (int i = 0; i < vpnsSize; i++) {
3885 Vpn vpn = mVpns.valueAt(i);
3886 vpn.onUserAdded(userId);
3887 }
3888 }
3889 }
3890
3891 private void onUserRemoved(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.onUserRemoved(userId);
3897 }
3898 }
3899 }
3900
Robin Lee89e7a692016-02-29 14:38:17 +00003901 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003902 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3903 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3904 updateLockdownVpn();
3905 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003906 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003907 }
3908 }
3909
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003910 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3911 @Override
3912 public void onReceive(Context context, Intent intent) {
3913 final String action = intent.getAction();
3914 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3915 if (userId == UserHandle.USER_NULL) return;
3916
Robin Lee323f29d2016-05-04 16:38:06 +01003917 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003919 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003920 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003921 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3922 onUserAdded(userId);
3923 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3924 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003925 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3926 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003927 }
3928 }
3929 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003930
Robin Lee95204e02017-01-27 11:59:22 +00003931 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3932 @Override
3933 public void onReceive(Context context, Intent intent) {
3934 // Try creating lockdown tracker, since user present usually means
3935 // unlocked keystore.
3936 updateLockdownVpn();
3937 mContext.unregisterReceiver(this);
3938 }
3939 };
3940
Robert Greenwalta67be032014-05-16 15:49:14 -07003941 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3942 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003943 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3944 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003945
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003946 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3947 // Map from UID to number of NetworkRequests that UID has filed.
3948 @GuardedBy("mUidToNetworkRequestCount")
3949 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3950
Robert Greenwalta67be032014-05-16 15:49:14 -07003951 private static class NetworkFactoryInfo {
3952 public final String name;
3953 public final Messenger messenger;
3954 public final AsyncChannel asyncChannel;
3955
3956 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3957 this.name = name;
3958 this.messenger = messenger;
3959 this.asyncChannel = asyncChannel;
3960 }
3961 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003962
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003963 private void ensureNetworkRequestHasType(NetworkRequest request) {
3964 if (request.type == NetworkRequest.Type.NONE) {
3965 throw new IllegalArgumentException(
3966 "All NetworkRequests in ConnectivityService must have a type");
3967 }
3968 }
3969
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003970 /**
3971 * Tracks info about the requester.
3972 * Also used to notice when the calling process dies so we can self-expire
3973 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003974 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003976 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003977 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003978 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003979 final int mPid;
3980 final int mUid;
3981 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003982
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003983 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003984 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003985 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003986 mPendingIntent = pi;
3987 messenger = null;
3988 mBinder = null;
3989 mPid = getCallingPid();
3990 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003991 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003992 }
3993
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003994 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003995 super();
3996 messenger = m;
3997 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003998 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 mBinder = binder;
4000 mPid = getCallingPid();
4001 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004002 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004003 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004004
4005 try {
4006 mBinder.linkToDeath(this, 0);
4007 } catch (RemoteException e) {
4008 binderDied();
4009 }
4010 }
4011
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004012 private void enforceRequestCountLimit() {
4013 synchronized (mUidToNetworkRequestCount) {
4014 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4015 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004016 throw new ServiceSpecificException(
4017 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004018 }
4019 mUidToNetworkRequestCount.put(mUid, networkRequests);
4020 }
4021 }
4022
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 if (mBinder != null) {
4025 mBinder.unlinkToDeath(this, 0);
4026 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 }
4028
4029 public void binderDied() {
4030 log("ConnectivityService NetworkRequestInfo binderDied(" +
4031 request + ", " + mBinder + ")");
4032 releaseNetworkRequest(request);
4033 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004034
4035 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004036 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004037 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004038 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 }
4040
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004041 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4042 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4043 if (badCapability != null) {
4044 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004045 }
4046 }
4047
Erik Kline9d598e12015-07-13 16:37:51 +09004048 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004049 final SortedSet<Integer> thresholds = new TreeSet();
4050 synchronized (nai) {
4051 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4052 if (nri.request.networkCapabilities.hasSignalStrength() &&
4053 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4054 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4055 }
4056 }
4057 }
Erik Kline9d598e12015-07-13 16:37:51 +09004058 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004059 }
4060
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004061 private void updateSignalStrengthThresholds(
4062 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4063 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004064 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004065 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4066
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004067 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004068 String detail;
4069 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4070 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4071 } else {
4072 detail = reason;
4073 }
4074 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4075 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4076 }
4077
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004078 nai.asyncChannel.sendMessage(
4079 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004080 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004081 }
4082
Etan Cohen859748f2017-04-03 17:42:34 -07004083 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4084 if (nc == null) {
4085 return;
4086 }
4087 NetworkSpecifier ns = nc.getNetworkSpecifier();
4088 if (ns == null) {
4089 return;
4090 }
4091 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4092 ns.assertValidFromUid(Binder.getCallingUid());
4093 }
4094
Robert Greenwalt9258c642014-03-26 16:47:06 -07004095 @Override
4096 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004097 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004098 final NetworkRequest.Type type = (networkCapabilities == null)
4099 ? NetworkRequest.Type.TRACK_DEFAULT
4100 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004101 // If the requested networkCapabilities is null, take them instead from
4102 // the default network request. This allows callers to keep track of
4103 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004104 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004105 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4106 enforceAccessPermission();
4107 } else {
4108 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4109 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004110 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4111 // of the app when the request is filed, but we never change the request if the app
4112 // changes network state. http://b/29964605
4113 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004114 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004115 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004116
Etan Cohenba07c8c2017-02-05 10:42:27 -08004117 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004118 throw new IllegalArgumentException("Bad timeout specified");
4119 }
Etan Cohen859748f2017-04-03 17:42:34 -07004120 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004121
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004122 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004123 nextNetworkRequestId(), type);
4124 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004125 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004126
4127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004128 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004129 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004130 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131 }
4132 return networkRequest;
4133 }
4134
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004136 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004137 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004138 } else {
4139 enforceChangePermission();
4140 }
4141 }
4142
fenglub15e72b2015-03-20 11:29:56 -07004143 @Override
fengludb571472015-04-21 17:12:05 -07004144 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004145 enforceAccessPermission();
4146 NetworkAgentInfo nai = null;
4147 if (network == null) {
4148 return false;
4149 }
4150 synchronized (mNetworkForNetId) {
4151 nai = mNetworkForNetId.get(network.netId);
4152 }
4153 if (nai != null) {
4154 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4155 return true;
4156 }
4157 return false;
4158 }
4159
Felipe Lemeee27cab2016-06-20 16:36:29 -07004160 private boolean isSystem(int uid) {
4161 return uid < Process.FIRST_APPLICATION_UID;
4162 }
fenglub15e72b2015-03-20 11:29:56 -07004163
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004164 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004165 final int uid = Binder.getCallingUid();
4166 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004167 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004168 return;
4169 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004170 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4171 // Policy already enforced.
4172 return;
4173 }
4174 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4175 // If UID is restricted, don't allow them to bring up metered APNs.
4176 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004177 }
4178 }
4179
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180 @Override
4181 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4182 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004183 checkNotNull(operation, "PendingIntent cannot be null.");
4184 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4185 enforceNetworkRequestPermissions(networkCapabilities);
4186 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004187 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004188 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004189
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004191 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4192 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004193 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004194 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4195 nri));
4196 return networkRequest;
4197 }
4198
Jeremy Joslin79294842014-12-03 17:15:28 -08004199 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4200 mHandler.sendMessageDelayed(
4201 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4202 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4203 }
4204
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004205 @Override
4206 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004207 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4209 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004210 }
4211
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004212 // In order to implement the compatibility measure for pre-M apps that call
4213 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4214 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4215 // This ensures it has permission to do so.
4216 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4217 if (nc == null) {
4218 return false;
4219 }
4220 int[] transportTypes = nc.getTransportTypes();
4221 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4222 return false;
4223 }
4224 try {
4225 mContext.enforceCallingOrSelfPermission(
4226 android.Manifest.permission.ACCESS_WIFI_STATE,
4227 "ConnectivityService");
4228 } catch (SecurityException e) {
4229 return false;
4230 }
4231 return true;
4232 }
4233
Robert Greenwalt9258c642014-03-26 16:47:06 -07004234 @Override
4235 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4236 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004237 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4238 enforceAccessPermission();
4239 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004241 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4242 if (!ConnectivityManager.checkChangePermission(mContext)) {
4243 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4244 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4245 // onLost and onAvailable callbacks when networks move in and out of the background.
4246 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4247 // can't request networks.
4248 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4249 }
Etan Cohen859748f2017-04-03 17:42:34 -07004250 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004251
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004252 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004253 NetworkRequest.Type.LISTEN);
4254 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004255 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004256
4257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4258 return networkRequest;
4259 }
4260
4261 @Override
4262 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4263 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004264 checkNotNull(operation, "PendingIntent cannot be null.");
4265 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4266 enforceAccessPermission();
4267 }
Etan Cohen859748f2017-04-03 17:42:34 -07004268 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004269
Erik Kline7523eb32015-07-09 18:24:03 +09004270 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004271 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4272 NetworkRequest.Type.LISTEN);
4273 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004274 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004275
4276 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 }
4278
Erik Klineacdd6392016-07-07 16:50:58 +09004279 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004281 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004282 mHandler.sendMessage(mHandler.obtainMessage(
4283 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004284 }
4285
4286 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004287 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004288 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004289 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4290 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004291 }
4292
Robert Greenwalta67be032014-05-16 15:49:14 -07004293 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004294 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004295 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4296 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4297 }
4298
4299 @Override
4300 public void unregisterNetworkFactory(Messenger messenger) {
4301 enforceConnectivityInternalPermission();
4302 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4303 }
4304
4305 private void handleUnregisterNetworkFactory(Messenger messenger) {
4306 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4307 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004308 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004309 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004310 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004311 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004312 }
4313
Robert Greenwalt7b816022014-04-18 15:25:25 -07004314 /**
4315 * NetworkAgentInfo supporting a request by requestId.
4316 * These have already been vetted (their Capabilities satisfy the request)
4317 * and the are the highest scored network available.
4318 * the are keyed off the Requests requestId.
4319 */
Hugo Benichicd952782017-09-20 11:20:14 +09004320 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4321 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004322 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4323 new SparseArray<NetworkAgentInfo>();
4324
Paul Jensen31a94f42015-02-13 14:18:39 -05004325 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4326 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4328 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004329 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4330 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4331 // there may not be a strict 1:1 correlation between the two.
4332 @GuardedBy("mNetworkForNetId")
4333 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004334
Robert Greenwalt7b816022014-04-18 15:25:25 -07004335 // NetworkAgentInfo keyed off its connecting messenger
4336 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004337 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004338 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4339 new HashMap<Messenger, NetworkAgentInfo>();
4340
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004341 @GuardedBy("mBlockedAppUids")
4342 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4343
Paul Jensen2c311d62014-11-17 12:34:51 -05004344 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004345 private final NetworkRequest mDefaultRequest;
4346
Erik Klineda4bfa82015-04-30 12:58:40 +09004347 // Request used to optionally keep mobile data active even when higher
4348 // priority networks like Wi-Fi are active.
4349 private final NetworkRequest mDefaultMobileDataRequest;
4350
Hugo Benichicd952782017-09-20 11:20:14 +09004351 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4352 synchronized (mNetworkForRequestId) {
4353 return mNetworkForRequestId.get(requestId);
4354 }
4355 }
4356
4357 private void clearNetworkForRequest(int requestId) {
4358 synchronized (mNetworkForRequestId) {
4359 mNetworkForRequestId.remove(requestId);
4360 }
4361 }
4362
4363 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4364 synchronized (mNetworkForRequestId) {
4365 mNetworkForRequestId.put(requestId, nai);
4366 }
4367 }
4368
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004369 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004370 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004371 }
4372
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004373 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004374 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004375 }
4376
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004377 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4378 return nri.request.requestId == mDefaultRequest.requestId;
4379 }
4380
Paul Jensen31a94f42015-02-13 14:18:39 -05004381 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004382 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004383 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 enforceConnectivityInternalPermission();
4385
Rubin Xu1bb5c082017-09-05 18:40:49 +01004386 LinkProperties lp = new LinkProperties(linkProperties);
4387 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004388 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4389 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004390 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004391 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4392 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004393 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004394 synchronized (this) {
4395 nai.networkMonitor.systemReady = mSystemReady;
4396 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004397 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4398 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004399 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004401 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
4403
4404 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4405 if (VDBG) log("Got NetworkAgent Messenger");
4406 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004407 synchronized (mNetworkForNetId) {
4408 mNetworkForNetId.put(na.network.netId, na);
4409 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4411 NetworkInfo networkInfo = na.networkInfo;
4412 na.networkInfo = null;
4413 updateNetworkInfo(na, networkInfo);
4414 }
4415
4416 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4417 LinkProperties newLp = networkAgent.linkProperties;
4418 int netId = networkAgent.network.netId;
4419
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004420 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4421 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004422 if (networkAgent.clatd != null) {
4423 networkAgent.clatd.fixupLinkProperties(oldLp);
4424 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004425
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004426 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004427 updateMtu(newLp, oldLp);
4428 // TODO - figure out what to do for clat
4429// for (LinkProperties lp : newLp.getStackedLinks()) {
4430// updateMtu(lp, null);
4431// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004432 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004433
Erik Kline94887872016-04-05 13:30:49 +09004434 updateRoutes(newLp, oldLp, netId);
4435 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004436
Hugo Benichib577d652017-06-27 15:13:20 +09004437 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004438 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004439 if (isDefaultNetwork(networkAgent)) {
4440 handleApplyDefaultProxy(newLp.getHttpProxy());
4441 } else {
4442 updateProxy(newLp, oldLp, networkAgent);
4443 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004444 // TODO - move this check to cover the whole function
4445 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004446 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004447 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4448 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004449
4450 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004451 }
4452
Joel Scherpelz668370b2017-06-08 15:35:21 +09004453 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004454 // Marks are only available on WiFi interaces. Checking for
4455 // marks on unsupported interfaces is harmless.
4456 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4457 return;
4458 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004459
Joel Scherpelz668370b2017-06-08 15:35:21 +09004460 int mark = mContext.getResources().getInteger(
4461 com.android.internal.R.integer.config_networkWakeupPacketMark);
4462 int mask = mContext.getResources().getInteger(
4463 com.android.internal.R.integer.config_networkWakeupPacketMask);
4464
4465 // Mask/mark of zero will not detect anything interesting.
4466 // Don't install rules unless both values are nonzero.
4467 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004468 return;
4469 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004470
4471 final String prefix = "iface:" + iface;
4472 try {
4473 if (add) {
4474 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4475 } else {
4476 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4477 }
4478 } catch (Exception e) {
4479 loge("Exception modifying wakeup packet monitoring: " + e);
4480 }
4481
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004482 }
4483
4484 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4485 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004486 CompareResult<String> interfaceDiff = new CompareResult<String>(
4487 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4488 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004489 for (String iface : interfaceDiff.added) {
4490 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004491 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004492 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004493 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004494 } catch (Exception e) {
4495 loge("Exception adding interface: " + e);
4496 }
4497 }
4498 for (String iface : interfaceDiff.removed) {
4499 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004500 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004501 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004502 mNetd.removeInterfaceFromNetwork(iface, netId);
4503 } catch (Exception e) {
4504 loge("Exception removing interface: " + e);
4505 }
4506 }
4507 }
4508
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004509 /**
4510 * Have netd update routes from oldLp to newLp.
4511 * @return true if routes changed between oldLp and newLp
4512 */
4513 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004514 // Compare the route diff to determine which routes should be added and removed.
4515 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4516 oldLp != null ? oldLp.getAllRoutes() : null,
4517 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004518
4519 // add routes before removing old in case it helps with continuous connectivity
4520
4521 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4522 for (RouteInfo route : routeDiff.added) {
4523 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004524 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 try {
4526 mNetd.addRoute(netId, route);
4527 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004528 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4529 loge("Exception in addRoute for non-gateway: " + e);
4530 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 }
4532 }
4533 for (RouteInfo route : routeDiff.added) {
4534 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004535 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 try {
4537 mNetd.addRoute(netId, route);
4538 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004539 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4540 loge("Exception in addRoute for gateway: " + e);
4541 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 }
4543 }
4544
4545 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004546 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547 try {
4548 mNetd.removeRoute(netId, route);
4549 } catch (Exception e) {
4550 loge("Exception in removeRoute: " + e);
4551 }
4552 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004553 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
Erik Kline41368502015-06-17 13:19:54 +09004555
Erik Kline94887872016-04-05 13:30:49 +09004556 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4557 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4558 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 }
Erik Kline94887872016-04-05 13:30:49 +09004560
4561 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004562 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004563 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004564 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004565 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4566 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004567 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004568 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004569 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4570 if (defaultNai != null && defaultNai.network.netId == netId) {
4571 setDefaultDnsSystemProperties(dnses);
4572 }
Erik Kline94887872016-04-05 13:30:49 +09004573 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 }
4575
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004576 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4577 int last = 0;
4578 for (InetAddress dns : dnses) {
4579 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004580 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004581 }
4582 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004583 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004584 }
4585 mNumDnsEntries = last;
4586 }
4587
Erik Kline4edba012017-04-07 15:29:29 +09004588 private void setNetDnsProperty(int which, String value) {
4589 final String key = "net.dns" + which;
4590 // Log and forget errors setting unsupported properties.
4591 try {
4592 mSystemProperties.set(key, value);
4593 } catch (Exception e) {
4594 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4595 }
4596 }
4597
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004598 private String getNetworkPermission(NetworkCapabilities nc) {
4599 // TODO: make these permission strings AIDL constants instead.
4600 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4601 return NetworkManagementService.PERMISSION_SYSTEM;
4602 }
4603 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4604 return NetworkManagementService.PERMISSION_NETWORK;
4605 }
4606 return null;
4607 }
4608
Paul Jensen3d194ea2015-06-16 14:27:36 -04004609 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004610 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4611 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4612 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004613 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004614 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004615 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004616 if (nai.everConnected &&
4617 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4618 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004619 // does not cause any request (that is not a listen) currently matching that agent to
4620 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004621 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004622 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004623 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004624 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004625 }
4626
Paul Jensen3d194ea2015-06-16 14:27:36 -04004627 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004628 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004629 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004630 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004631 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004632 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004633 }
Paul Jensene0988542015-06-25 15:30:08 -04004634 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004635 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004636 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004637 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004638 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004639 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004640 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004641 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004642 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004643 }
4644
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004645 return newNc;
4646 }
4647
4648 /**
4649 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4650 *
4651 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4652 * capabilities we manage and store in {@code nai}, such as validated status and captive
4653 * portal status)
4654 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4655 * potentially triggers rematches.
4656 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4657 * change.)
4658 *
4659 * @param oldScore score of the network before any of the changes that prompted us
4660 * to call this function.
4661 * @param nai the network having its capabilities updated.
4662 * @param nc the new network capabilities.
4663 */
4664 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4665 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4666
4667 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004668
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004669 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004670 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004671 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004672 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004673 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004674 } catch (RemoteException e) {
4675 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004676 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004677 }
4678
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004679 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004680 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004681 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004682 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004683 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004684
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004685 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004686 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4687 // the change we're processing can't affect any requests, it can only affect the listens
4688 // on this network. We might have been called by rematchNetworkAndRequests when a
4689 // network changed foreground state.
4690 processListenRequests(nai, true);
4691 } else {
4692 // If the requestable capabilities have changed or the score changed, we can't have been
4693 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004694 rematchAllNetworksAndRequests(nai, oldScore);
4695 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004696 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004697
4698 // Report changes that are interesting for network statistics tracking.
4699 if (prevNc != null) {
4700 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004701 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004702 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004703 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004704 if (meteredChanged || roamingChanged) {
4705 notifyIfacesChangedForNetworkStats();
4706 }
4707 }
4708
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004709 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004710 // Tell VPNs about updated capabilities, since they may need to
4711 // bubble those changes through.
4712 synchronized (mVpns) {
4713 for (int i = 0; i < mVpns.size(); i++) {
4714 final Vpn vpn = mVpns.valueAt(i);
4715 vpn.updateCapabilities();
4716 }
4717 }
4718 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004719 }
4720
Hugo Benichief502882017-09-01 01:23:32 +00004721 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4722 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4723 // Ignore updates for disconnected networks
4724 return;
4725 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004726 // newLp is already a defensive copy.
4727 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004728 if (VDBG) {
4729 log("Update of LinkProperties for " + nai.name() +
4730 "; created=" + nai.created +
4731 "; everConnected=" + nai.everConnected);
4732 }
4733 LinkProperties oldLp = nai.linkProperties;
4734 synchronized (nai) {
4735 nai.linkProperties = newLp;
4736 }
4737 if (nai.everConnected) {
4738 updateLinkProperties(nai, oldLp);
4739 }
4740 }
4741
Paul Jensenc8b9a742014-09-30 15:37:41 -04004742 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004743 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4744 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004745 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004746 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004747 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4748 }
4749 }
4750
Robert Greenwalt7b816022014-04-18 15:25:25 -07004751 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4752 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004753 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004754 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4755 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004756 }
4757 }
4758
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004759 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4760 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004761 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004762 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004763 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4764 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004765 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004766 sendIntent(nri.mPendingIntent, intent);
4767 }
4768 // else not handled
4769 }
4770
4771 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4772 mPendingIntentWakeLock.acquire();
4773 try {
4774 if (DBG) log("Sending " + pendingIntent);
4775 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4776 } catch (PendingIntent.CanceledException e) {
4777 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4778 mPendingIntentWakeLock.release();
4779 releasePendingNetworkRequest(pendingIntent);
4780 }
4781 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4782 }
4783
4784 @Override
4785 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4786 String resultData, Bundle resultExtras) {
4787 if (DBG) log("Finished sending " + pendingIntent);
4788 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004789 // Release with a delay so the receiving client has an opportunity to put in its
4790 // own request.
4791 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004792 }
4793
Hugo Benichidba33db2017-03-23 22:40:44 +09004794 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004795 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004796 if (nri.messenger == null) {
4797 return; // Default request has no msgr
4798 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004799 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004800 // TODO: check if defensive copies of data is needed.
4801 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004802 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004803 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4804 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004805 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004806 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004807 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004808 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004809 break;
4810 }
4811 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004812 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004813 break;
4814 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004815 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004816 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004817 break;
4818 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004819 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004820 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004821 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004822 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004823 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004824 String notification = ConnectivityManager.getCallbackName(notificationType);
4825 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004826 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004827 nri.messenger.send(msg);
4828 } catch (RemoteException e) {
4829 // may occur naturally in the race of binder death.
4830 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4831 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004832 }
4833
Hugo Benichidba33db2017-03-23 22:40:44 +09004834 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4835 bundle.putParcelable(t.getClass().getSimpleName(), t);
4836 }
4837
Paul Jensenc8b9a742014-09-30 15:37:41 -04004838 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004839 if (nai.numRequestNetworkRequests() != 0) {
4840 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4841 NetworkRequest nr = nai.requestAt(i);
4842 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004843 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004844 loge("Dead network still had at least " + nr);
4845 break;
4846 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004847 }
4848 nai.asyncChannel.disconnect();
4849 }
4850
Robert Greenwalt7b816022014-04-18 15:25:25 -07004851 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4852 if (oldNetwork == null) {
4853 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4854 return;
4855 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004856 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004857
4858 // If we get here it means that the last linger timeout for this network expired. So there
4859 // must be no other active linger timers, and we must stop lingering.
4860 oldNetwork.clearLingerState();
4861
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004862 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004864 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004865 } else {
4866 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004867 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4868 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004869 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 }
4871
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004872 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004873 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004874 setupDataActivityTracking(newNetwork);
4875 try {
4876 mNetd.setDefaultNetId(newNetwork.network.netId);
4877 } catch (Exception e) {
4878 loge("Exception setting default network :" + e);
4879 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004880 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004881 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004882 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004883 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004884 }
4885
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004886 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004887 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4888 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4889 NetworkRequest nr = nri.request;
4890 if (!nr.isListen()) continue;
4891 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4892 nai.removeRequest(nri.request.requestId);
4893 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4894 }
4895 }
4896
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004897 if (capabilitiesChanged) {
4898 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4899 }
4900
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004901 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4902 NetworkRequest nr = nri.request;
4903 if (!nr.isListen()) continue;
4904 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4905 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004906 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004907 }
4908 }
4909 }
4910
Paul Jensen2161a8e2014-09-11 11:00:39 -04004911 // Handles a network appearing or improving its score.
4912 //
4913 // - Evaluates all current NetworkRequests that can be
4914 // satisfied by newNetwork, and reassigns to newNetwork
4915 // any such requests for which newNetwork is the best.
4916 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004917 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004918 // needed. A network is needed if it is the best network for
4919 // one or more NetworkRequests, or if it is a VPN.
4920 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004921 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004922 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004923 //
4924 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4925 // networks that have no chance (i.e. even if validated)
4926 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004927 //
4928 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4929 // it does not remove NetworkRequests that other Networks could better satisfy.
4930 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4931 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4932 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004933 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004934 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004935 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4936 // performed to tear down unvalidated networks that have no chance (i.e. even if
4937 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004938 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004939 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004940 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004941 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004943 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004944
4945 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4946 final int score = newNetwork.getCurrentScore();
4947
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004948 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004949
Paul Jensen2161a8e2014-09-11 11:00:39 -04004950 // Find and migrate to this Network any NetworkRequests for
4951 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004953 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004954 NetworkCapabilities nc = newNetwork.networkCapabilities;
4955 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004956 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004957 // Process requests in the first pass and listens in the second pass. This allows us to
4958 // change a network's capabilities depending on which requests it has. This is only
4959 // correct if the change in capabilities doesn't affect whether the network satisfies
4960 // requests or not, and doesn't affect the network's score.
4961 if (nri.request.isListen()) continue;
4962
Hugo Benichicd952782017-09-20 11:20:14 +09004963 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004964 final boolean satisfies = newNetwork.satisfies(nri.request);
4965 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004966 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004967 log("Network " + newNetwork.name() + " was already satisfying" +
4968 " request " + nri.request.requestId + ". No change.");
4969 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004970 keep = true;
4971 continue;
4972 }
4973
4974 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004975 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004976 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004977 // next check if it's better than any current network we're using for
4978 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004979 if (VDBG) {
4980 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004981 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004982 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004984 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004985 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004986 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004987 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004988 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004989 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004990 affectedNetworks.add(currentNetwork);
4991 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004992 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004994 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09004995 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004996 if (!newNetwork.addRequest(nri.request)) {
4997 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4998 }
4999 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005000 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005001 // Tell NetworkFactories about the new score, so they can stop
5002 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005003 // TODO - this could get expensive if we have alot of requests for this
5004 // network. Think about if there is a way to reduce this. Push
5005 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005006 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005007 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005008 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005009 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005010 if (currentNetwork != null) {
5011 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5012 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005013 }
5014 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005015 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005016 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5017 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005018 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005019 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5020 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5021 // This means this code doesn't have to handle the case where "currentNetwork" no
5022 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5023 if (DBG) {
5024 log("Network " + newNetwork.name() + " stopped satisfying" +
5025 " request " + nri.request.requestId);
5026 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005027 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005028 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005029 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005030 sendUpdatedScoreToFactories(nri.request, 0);
5031 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005032 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5033 newNetwork.name() +
5034 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005035 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005036 // TODO: Technically, sending CALLBACK_LOST here is
5037 // incorrect if there is a replacement network currently
5038 // connected that can satisfy nri, which is a request
5039 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005040 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5041 // so this code is only incorrect for a network that loses
5042 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005043 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005044 }
5045 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005046 if (isNewDefault) {
5047 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005048 makeDefault(newNetwork);
5049 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005050 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005051 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005052 // Have a new default network, release the transition wakelock in
5053 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005054 }
5055
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005056 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5057 Slog.wtf(TAG, String.format(
5058 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005059 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005060 }
5061 if (newNetwork.getCurrentScore() != score) {
5062 Slog.wtf(TAG, String.format(
5063 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005064 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005065 }
5066
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005067 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005068 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5069 // If the network went from background to foreground or vice versa, we need to update
5070 // its foreground state. It is safe to do this after rematching the requests because
5071 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5072 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005073 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005074 } else {
5075 processListenRequests(newNetwork, false);
5076 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005077
Paul Jensencf4c2c62015-07-01 14:16:32 -04005078 // do this after the default net is switched, but
5079 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005080 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005081
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005082 // Linger any networks that are no longer needed. This should be done after sending the
5083 // available callback for newNetwork.
5084 for (NetworkAgentInfo nai : affectedNetworks) {
5085 updateLingerState(nai, now);
5086 }
5087 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5088 // does not need to be done in any particular order.
5089 updateLingerState(newNetwork, now);
5090
Paul Jensencf4c2c62015-07-01 14:16:32 -04005091 if (isNewDefault) {
5092 // Maintain the illusion: since the legacy API only
5093 // understands one network at a time, we must pretend
5094 // that the current default network disconnected before
5095 // the new one connected.
5096 if (oldDefaultNetwork != null) {
5097 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5098 oldDefaultNetwork, true);
5099 }
5100 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5101 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5102 notifyLockdownVpn(newNetwork);
5103 }
5104
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005106 // Notify battery stats service about this network, both the normal
5107 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005108 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005109 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005110 final IBatteryStats bs = BatteryStatsService.getService();
5111 final int type = newNetwork.networkInfo.getType();
5112
5113 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5114 bs.noteNetworkInterfaceType(baseIface, type);
5115 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5116 final String stackedIface = stacked.getInterfaceName();
5117 bs.noteNetworkInterfaceType(stackedIface, type);
5118 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5119 }
5120 } catch (RemoteException ignored) {
5121 }
5122
Robert Greenwalt152ed372014-12-17 17:19:53 -08005123 // This has to happen after the notifyNetworkCallbacks as that tickles each
5124 // ConnectivityManager instance so that legacy requests correctly bind dns
5125 // requests to this network. The legacy users are listening for this bcast
5126 // and will generally do a dns request so they can ensureRouteToHost and if
5127 // they do that before the callbacks happen they'll use the default network.
5128 //
5129 // TODO: Is there still a race here? We send the broadcast
5130 // after sending the callback, but if the app can receive the
5131 // broadcast before the callback, it might still break.
5132 //
5133 // This *does* introduce a race where if the user uses the new api
5134 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5135 // they may get old info. Reverse this after the old startUsing api is removed.
5136 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005137 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5138 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005139 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005140 // legacy type tracker filters out repeat adds
5141 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5142 }
5143 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005144
5145 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5146 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5147 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5148 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5149 if (newNetwork.isVPN()) {
5150 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5151 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005152 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005153 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5154 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005155 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005156 if (nai.getLingerExpiry() > 0) {
5157 // This network has active linger timers and no requests, but is not
5158 // lingering. Linger it.
5159 //
5160 // One way (the only way?) this can happen if this network is unvalidated
5161 // and became unneeded due to another network improving its score to the
5162 // point where this network will no longer be able to satisfy any requests
5163 // even if it validates.
5164 updateLingerState(nai, now);
5165 } else {
5166 if (DBG) log("Reaping " + nai.name());
5167 teardownUnneededNetwork(nai);
5168 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005169 }
5170 }
5171 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 }
5173
Paul Jensen1c7ba022015-06-16 14:27:36 -04005174 /**
5175 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5176 * being disconnected.
5177 * @param changed If only one Network's score or capabilities have been modified since the last
5178 * time this function was called, pass this Network in this argument, otherwise pass
5179 * null.
5180 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5181 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5182 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5183 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5184 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005185 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005186 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005187 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5188 // to avoid the slowness. It is not simply enough to process just "changed", for
5189 // example in the case where "changed"'s score decreases and another network should begin
5190 // satifying a NetworkRequest that "changed" currently satisfies.
5191
5192 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5193 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5194 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005195 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005196 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005197 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005198 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005199 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5200 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5201 // Rematch higher scoring networks first to prevent requests first matching a lower
5202 // scoring network and then a higher scoring network, which could produce multiple
5203 // callbacks and inadvertently unlinger networks.
5204 Arrays.sort(nais);
5205 for (NetworkAgentInfo nai : nais) {
5206 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005207 // Only reap the last time through the loop. Reaping before all rematching
5208 // is complete could incorrectly teardown a network that hasn't yet been
5209 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005210 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005211 : ReapUnvalidatedNetworks.REAP,
5212 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005213 }
5214 }
5215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005216
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005217 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005218 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005219 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005220 // For now only update icons for default connection.
5221 // TODO: Update WiFi and cellular icons separately. b/17237507
5222 if (!isDefaultNetwork(nai)) return;
5223
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005224 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005225 // Don't repeat publish.
5226 if (newInetCondition == mDefaultInetConditionPublished) return;
5227
5228 mDefaultInetConditionPublished = newInetCondition;
5229 sendInetConditionBroadcast(nai.networkInfo);
5230 }
5231
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005232 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5233 if (mLockdownTracker != null) {
5234 if (nai != null && nai.isVPN()) {
5235 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5236 } else {
5237 mLockdownTracker.onNetworkInfoChanged();
5238 }
5239 }
5240 }
5241
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005243 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005244 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005245 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005246 synchronized (networkAgent) {
5247 oldInfo = networkAgent.networkInfo;
5248 networkAgent.networkInfo = newInfo;
5249 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005250 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005251
Robert Greenwalt7b816022014-04-18 15:25:25 -07005252 if (DBG) {
5253 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5254 (oldInfo == null ? "null" : oldInfo.getState()) +
5255 " to " + state);
5256 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005257
Robin Lee585e2482016-05-01 23:00:00 +01005258 if (!networkAgent.created
5259 && (state == NetworkInfo.State.CONNECTED
5260 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005261
5262 // A network that has just connected has zero requests and is thus a foreground network.
5263 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5264
Robert Greenwalt7b816022014-04-18 15:25:25 -07005265 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005266 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005267 if (networkAgent.isVPN()) {
5268 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005269 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5270 (networkAgent.networkMisc == null ||
5271 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005272 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005273 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005274 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005275 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005276 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005277 loge("Error creating network " + networkAgent.network.netId + ": "
5278 + e.getMessage());
5279 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005280 }
Paul Jenseneec75412014-08-04 12:21:19 -04005281 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005282 }
5283
5284 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5285 networkAgent.everConnected = true;
5286
Robert Greenwalt7b816022014-04-18 15:25:25 -07005287 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005288 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005289
Paul Jensenca8f16a2014-05-09 12:47:55 -04005290 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005291 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005292
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005293 if (networkAgent.isVPN()) {
5294 // Temporarily disable the default proxy (not global).
5295 synchronized (mProxyLock) {
5296 if (!mDefaultProxyDisabled) {
5297 mDefaultProxyDisabled = true;
5298 if (mGlobalProxy == null && mDefaultProxy != null) {
5299 sendProxyBroadcast(null);
5300 }
5301 }
5302 }
5303 // TODO: support proxy per network.
5304 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005305
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005306 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5307 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5308 // capabilities, so it only needs to be done once on initial connect, not every time the
5309 // network's capabilities change. Note that we do this before rematching the network,
5310 // so we could decide to tear it down immediately afterwards. That's fine though - on
5311 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5312 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005313 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005314
Paul Jensen2161a8e2014-09-11 11:00:39 -04005315 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005316 final long now = SystemClock.elapsedRealtime();
5317 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005318
5319 // This has to happen after matching the requests, because callbacks are just requests.
5320 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005321 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005322 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005323 if (networkAgent.isVPN()) {
5324 synchronized (mProxyLock) {
5325 if (mDefaultProxyDisabled) {
5326 mDefaultProxyDisabled = false;
5327 if (mGlobalProxy == null && mDefaultProxy != null) {
5328 sendProxyBroadcast(mDefaultProxy);
5329 }
5330 }
5331 }
5332 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005333 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5334 state == NetworkInfo.State.SUSPENDED) {
5335 // going into or coming out of SUSPEND: rescore and notify
5336 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005337 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005338 }
5339 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5340 ConnectivityManager.CALLBACK_SUSPENDED :
5341 ConnectivityManager.CALLBACK_RESUMED));
5342 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005343 }
5344 }
5345
Robert Greenwaltac96c522014-06-03 16:43:57 -07005346 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005347 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005348 if (score < 0) {
5349 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5350 "). Bumping score to min of 0");
5351 score = 0;
5352 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005353
Paul Jensen2161a8e2014-09-11 11:00:39 -04005354 final int oldScore = nai.getCurrentScore();
5355 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005356
Paul Jensen85cf78e2015-06-25 13:25:07 -04005357 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005358
Paul Jensenc8b9a742014-09-30 15:37:41 -04005359 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005360 }
5361
Erik Klinec75d4fa2017-02-15 19:59:17 +09005362 // Notify only this one new request of the current state. Transfer all the
5363 // current state by calling NetworkCapabilities and LinkProperties callbacks
5364 // so that callers can be guaranteed to have as close to atomicity in state
5365 // transfer as can be supported by this current API.
5366 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005367 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005368 if (nri.mPendingIntent != null) {
5369 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5370 // Attempt no subsequent state pushes where intents are involved.
5371 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005372 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005373
5374 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5375 // Whether a network is currently suspended is also an important
5376 // element of state to be transferred (it would not otherwise be
5377 // delivered by any currently available mechanism).
5378 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5379 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5380 }
5381 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5382 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005383 }
5384
Robert Greenwalt8d482522015-06-24 13:23:42 -07005385 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005386 // The NetworkInfo we actually send out has no bearing on the real
5387 // state of affairs. For example, if the default connection is mobile,
5388 // and a request for HIPRI has just gone away, we need to pretend that
5389 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5390 // the state to DISCONNECTED, even though the network is of type MOBILE
5391 // and is still connected.
5392 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5393 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005394 if (state != DetailedState.DISCONNECTED) {
5395 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005396 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005397 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005398 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005399 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5401 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5402 if (info.isFailover()) {
5403 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5404 nai.networkInfo.setFailover(false);
5405 }
5406 if (info.getReason() != null) {
5407 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5408 }
5409 if (info.getExtraInfo() != null) {
5410 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5411 }
5412 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005413 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005414 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005415 if (newDefaultAgent != null) {
5416 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5417 newDefaultAgent.networkInfo);
5418 } else {
5419 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5420 }
5421 }
5422 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5423 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005424 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005425 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005426 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005427 }
5428 }
5429 }
5430
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005431 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005432 if (VDBG) {
5433 String notification = ConnectivityManager.getCallbackName(notifyType);
5434 log("notifyType " + notification + " for " + networkAgent.name());
5435 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005436 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5437 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005438 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5439 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005440 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5441 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005442 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005443 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005444 } else {
5445 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5446 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005448 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005449
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005450 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5451 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5452 }
5453
Jeff Sharkey69736342014-12-08 14:50:12 -08005454 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005455 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5456 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005457 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005458 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005459 try {
5460 mStatsService.forceUpdateIfaces();
5461 } catch (Exception ignored) {
5462 }
5463 }
5464
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005465 @Override
5466 public boolean addVpnAddress(String address, int prefixLength) {
5467 throwIfLockdownEnabled();
5468 int user = UserHandle.getUserId(Binder.getCallingUid());
5469 synchronized (mVpns) {
5470 return mVpns.get(user).addAddress(address, prefixLength);
5471 }
5472 }
5473
5474 @Override
5475 public boolean removeVpnAddress(String address, int prefixLength) {
5476 throwIfLockdownEnabled();
5477 int user = UserHandle.getUserId(Binder.getCallingUid());
5478 synchronized (mVpns) {
5479 return mVpns.get(user).removeAddress(address, prefixLength);
5480 }
5481 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005482
5483 @Override
5484 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5485 throwIfLockdownEnabled();
5486 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005487 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005488 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005489 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005490 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005491 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005492 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005493 }
5494 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005495 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005496
5497 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005498 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005499 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005500 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005501 }
5502
5503 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005504 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5505 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5506 enforceKeepalivePermission();
5507 mKeepaliveTracker.startNattKeepalive(
5508 getNetworkAgentInfoForNetwork(network),
5509 intervalSeconds, messenger, binder,
5510 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5511 }
5512
5513 @Override
5514 public void stopKeepalive(Network network, int slot) {
5515 mHandler.sendMessage(mHandler.obtainMessage(
5516 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5517 }
5518
5519 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005520 public void factoryReset() {
5521 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005522
5523 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5524 return;
5525 }
5526
Robin Lee3b3dd942015-05-12 18:14:58 +01005527 final int userId = UserHandle.getCallingUserId();
5528
Stuart Scottf1fb3972015-04-02 18:00:02 -07005529 // Turn airplane mode off
5530 setAirplaneMode(false);
5531
Stuart Scotte3e314d2015-04-20 14:07:45 -07005532 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5533 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005534 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005535 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005536 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005537 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005538 }
5539
Stuart Scotte3e314d2015-04-20 14:07:45 -07005540 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005541 // Remove always-on package
5542 synchronized (mVpns) {
5543 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5544 if (alwaysOnPackage != null) {
5545 setAlwaysOnVpnPackage(userId, null, false);
5546 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5547 }
5548 }
5549
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005550 // Turn Always-on VPN off
5551 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5552 final long ident = Binder.clearCallingIdentity();
5553 try {
5554 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5555 mLockdownEnabled = false;
5556 setLockdownTracker(null);
5557 } finally {
5558 Binder.restoreCallingIdentity(ident);
5559 }
5560 }
5561
Stuart Scotte3e314d2015-04-20 14:07:45 -07005562 // Turn VPN off
5563 VpnConfig vpnConfig = getVpnConfig(userId);
5564 if (vpnConfig != null) {
5565 if (vpnConfig.legacy) {
5566 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5567 } else {
5568 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5569 // in the future without user intervention.
5570 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005571
Victor Changb04a5ea2016-05-30 20:36:30 +01005572 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005573 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005574 }
5575 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005576
5577 Settings.Global.putString(mContext.getContentResolver(),
5578 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005579 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005580
5581 @VisibleForTesting
5582 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5583 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5584 return new NetworkMonitor(context, handler, nai, defaultRequest);
5585 }
Erik Kline48f12f22016-04-14 17:30:59 +09005586
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005587 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005588 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5589 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005590 }
5591
5592 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005593 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5594 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5595 }
5596
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005597 @VisibleForTesting
5598 public boolean hasService(String name) {
5599 return ServiceManager.checkService(name) != null;
5600 }
5601
Hugo Benichi64901e52017-10-19 14:42:40 +09005602 @VisibleForTesting
5603 protected IpConnectivityMetrics.Logger metricsLogger() {
5604 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5605 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005606 }
5607
5608 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005609 int[] transports = nai.networkCapabilities.getTransportTypes();
5610 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005611 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005612
5613 private static boolean toBool(int encodedBoolean) {
5614 return encodedBoolean != 0; // Only 0 means false.
5615 }
5616
5617 private static int encodeBool(boolean b) {
5618 return b ? 1 : 0;
5619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620}