blob: f34730c084fcccf87819db086d407d95f07776c9 [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;
Erik Kline1742fe12017-12-13 19:40:49 +0900133import com.android.server.connectivity.DnsManager;
Hugo Benichi64901e52017-10-19 14:42:40 +0900134import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900135import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100136import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700137import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700138import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600139import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900141import com.android.server.connectivity.NetworkNotificationManager;
142import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400143import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700144import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800145import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700146import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900147import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700148import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700149import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900150import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600151
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700152import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700153
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import org.xmlpull.v1.XmlPullParser;
155import org.xmlpull.v1.XmlPullParserException;
156
157import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700159import java.io.FileNotFoundException;
160import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700161import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700163import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.net.InetAddress;
165import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700166import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700168import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700169import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700170import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700171import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700172import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700173import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700174import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600175import java.util.SortedSet;
176import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178/**
179 * @hide
180 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800181public class ConnectivityService extends IConnectivityManager.Stub
182 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900183 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Erik Kline7747fd42017-05-12 16:52:48 +0900185 public static final String DIAG_ARG = "--diag";
186 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900187 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900188
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900189 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700190 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Jake Hamby786e71a2014-02-06 14:43:50 -0800192 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900193 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700194
Jeff Sharkey899223b2012-08-04 15:24:58 -0700195 // TODO: create better separation between radio types and network types
196
Robert Greenwalt42acef32009-08-12 16:08:25 -0700197 // how long to wait before switching back to a radio's default network
198 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
199 // system property that can override the above value
200 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
201 "android.telephony.apn-restore";
202
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900203 // How long to wait before putting up a "This network doesn't have an Internet connection,
204 // connect anyway?" dialog after the user selects a network that doesn't validate.
205 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
206
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900207 // Default to 30s linger time-out. Modifiable only for testing.
208 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
209 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
210 @VisibleForTesting
211 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
212
Jeremy Joslin79294842014-12-03 17:15:28 -0800213 // How long to delay to removal of a pending intent based request.
214 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
215 private final int mReleasePendingIntentDelayMs;
216
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900217 private MockableSystemProperties mSystemProperties;
218
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800219 private Tethering mTethering;
220
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700221 private final PermissionMonitor mPermissionMonitor;
222
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700223 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700224
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700225 @GuardedBy("mVpns")
226 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700227
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700228 private boolean mLockdownEnabled;
229 private LockdownVpnTracker mLockdownTracker;
230
Erik Klineda4bfa82015-04-30 12:58:40 +0900231 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700233 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700234 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700237 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700239 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800240 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700241 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900242 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700243
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700244 private String mCurrentTcpBufferSizes;
245
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700246 private static final int ENABLED = 1;
247 private static final int DISABLED = 0;
248
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900249 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900250 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
251 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900252
Paul Jensenb10e37f2014-11-25 12:33:08 -0500253 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400254 // Tear down networks that have no chance (e.g. even if validated) of becoming
255 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 // all networks have been rematched against all NetworkRequests.
257 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400258 // Don't reap networks. This should be passed when some networks have not yet been
259 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500260 DONT_REAP
261 };
262
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900263 private enum UnneededFor {
264 LINGER, // Determine whether this network is unneeded and should be lingered.
265 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
266 }
267
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700268 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269 * used internally to change our mobile data enabled flag
270 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700271 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700272
273 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700274 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700275 * from one net to another. Clear happens when we get a new
276 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
277 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700280
Robert Greenwalt434203a2010-10-11 16:00:27 -0700281 /**
282 * used internally to reload global proxy settings
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700285
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700286 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400287 * PAC manager has received new port.
288 */
289 private static final int EVENT_PROXY_HAS_CHANGED = 16;
290
Robert Greenwalte049c232014-04-11 15:53:27 -0700291 /**
292 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700293 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700294 */
295 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
296
Robert Greenwalt7b816022014-04-18 15:25:25 -0700297 /**
298 * used internally when registering NetworkAgents
299 * obj = Messenger
300 */
301 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
302
Robert Greenwalt9258c642014-03-26 16:47:06 -0700303 /**
304 * used to add a network request
305 * includes a NetworkRequestInfo
306 */
307 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
308
309 /**
310 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900311 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700312 * cancel it.
313 * includes a NetworkRequestInfo
314 */
315 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
316
317 /**
318 * used to add a network listener - no request
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
322
323 /**
324 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400325 * arg1 = UID of caller
326 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700327 */
328 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
329
Robert Greenwalta67be032014-05-16 15:49:14 -0700330 /**
331 * used internally when registering NetworkFactories
332 * obj = Messenger
333 */
334 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
335
Robert Greenwalt27711812014-06-25 16:45:57 -0700336 /**
337 * used internally to expire a wakelock when transitioning
338 * from one net to another. Expire happens when we fail to find
339 * a new network (typically after 1 minute) -
340 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
341 * a replacement network.
342 */
343 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
344
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700345 /**
346 * Used internally to indicate the system is ready.
347 */
348 private static final int EVENT_SYSTEM_READY = 25;
349
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800350 /**
351 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400352 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800353 */
354 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
355
356 /**
357 * used to remove a pending intent and its associated network request.
358 * arg1 = UID of caller
359 * obj = PendingIntent
360 */
361 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
362
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900363 /**
364 * used to specify whether a network should be used even if unvalidated.
365 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
366 * arg2 = whether to remember this choice in the future (1 or 0)
367 * obj = network
368 */
369 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
370
371 /**
372 * used to ask the user to confirm a connection to an unvalidated network.
373 * obj = network
374 */
375 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700376
Erik Klineda4bfa82015-04-30 12:58:40 +0900377 /**
378 * used internally to (re)configure mobile data always-on settings.
379 */
380 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
381
Paul Jensen694f2b82015-06-17 14:15:39 -0400382 /**
383 * used to add a network listener with a pending intent
384 * obj = NetworkRequestInfo
385 */
386 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
387
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900388 /**
389 * used to specify whether a network should not be penalized when it becomes unvalidated.
390 */
391 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
392
393 /**
394 * used to trigger revalidation of a network.
395 */
396 private static final int EVENT_REVALIDATE_NETWORK = 36;
397
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900398 private static String eventName(int what) {
399 return sMagicDecoderRing.get(what, Integer.toString(what));
400 }
401
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900402 /** Handler thread used for both of the handlers below. */
403 @VisibleForTesting
404 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700407 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700408 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900409 private final DnsManager mDnsManager;
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();
Erik Kline1742fe12017-12-13 19:40:49 +0900860
861 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700863
Erik Kline47222fc2017-04-30 19:36:15 +0900864 private Tethering makeTethering() {
865 // TODO: Move other elements into @Overridden getters.
866 final TetheringDependencies deps = new TetheringDependencies();
867 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
868 IoThread.get().getLooper(), new MockableSystemProperties(),
869 deps);
870 }
871
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900872 private NetworkRequest createInternetRequestForTransport(
873 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900875 netCap.addCapability(NET_CAPABILITY_INTERNET);
876 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 if (transportType > -1) {
878 netCap.addTransportType(transportType);
879 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900880 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900881 }
882
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900883 // Used only for testing.
884 // TODO: Delete this and either:
885 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
886 // changing ContentResolver to make registerContentObserver non-final).
887 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
888 // by subclassing SettingsObserver.
889 @VisibleForTesting
890 void updateMobileDataAlwaysOn() {
891 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
892 }
893
Erik Klineda4bfa82015-04-30 12:58:40 +0900894 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900895 final boolean enable = toBool(Settings.Global.getInt(
896 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900897 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
898 if (enable == isEnabled) {
899 return; // Nothing to do.
900 }
901
902 if (enable) {
903 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900904 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900905 } else {
906 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
907 }
908 }
909
910 private void registerSettingsCallbacks() {
911 // Watch for global HTTP proxy changes.
912 mSettingsObserver.observe(
913 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
914 EVENT_APPLY_GLOBAL_HTTP_PROXY);
915
916 // Watch for whether or not to keep mobile data always on.
917 mSettingsObserver.observe(
918 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
919 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
920 }
921
Robert Greenwalt34524f02014-05-18 16:22:10 -0700922 private synchronized int nextNetworkRequestId() {
923 return mNextNetworkRequestId++;
924 }
925
Paul Jensen67b0b072015-06-10 11:22:17 -0400926 @VisibleForTesting
927 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400928 synchronized (mNetworkForNetId) {
929 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
930 int netId = mNextNetId;
931 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
932 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500933 if (!mNetIdInUse.get(netId)) {
934 mNetIdInUse.put(netId, true);
935 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400936 }
937 }
938 }
939 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700940 }
941
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600942 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
945 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600947 state = nai.getNetworkState();
948 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600950 final NetworkInfo info = new NetworkInfo(networkType, 0,
951 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
953 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700954 final NetworkCapabilities capabilities = new NetworkCapabilities();
955 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
956 !info.isRoaming());
957 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600958 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600960 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600961 return state;
962 } else {
963 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400965 }
966
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
968 if (network == null) {
969 return null;
970 }
971 synchronized (mNetworkForNetId) {
972 return mNetworkForNetId.get(network.netId);
973 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600974 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900976 private Network[] getVpnUnderlyingNetworks(int uid) {
977 if (!mLockdownEnabled) {
978 int user = UserHandle.getUserId(uid);
979 synchronized (mVpns) {
980 Vpn vpn = mVpns.get(user);
981 if (vpn != null && vpn.appliesToUid(uid)) {
982 return vpn.getUnderlyingNetworks();
983 }
984 }
985 }
986 return null;
987 }
988
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400990 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800991
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900992 final Network[] networks = getVpnUnderlyingNetworks(uid);
993 if (networks != null) {
994 // getUnderlyingNetworks() returns:
995 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
996 // empty array => the VPN explicitly said "no default network".
997 // non-empty array => the VPN specified one or more default networks; we use the
998 // first one.
999 if (networks.length > 0) {
1000 nai = getNetworkAgentInfoForNetwork(networks[0]);
1001 } else {
1002 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001003 }
1004 }
1005
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001006 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001007 return nai.getNetworkState();
1008 } else {
1009 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001011 }
1012
1013 /**
1014 * Check if UID should be blocked from using the network with the given LinkProperties.
1015 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001016 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1017 boolean ignoreBlocked) {
1018 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001019 if (ignoreBlocked) {
1020 return false;
1021 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001022 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001023 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1024 if (isSystem(uid)) {
1025 return false;
1026 }
Robin Lee17e61832016-05-09 13:46:28 +01001027 synchronized (mVpns) {
1028 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1029 if (vpn != null && vpn.isBlockingUid(uid)) {
1030 return true;
1031 }
1032 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001033 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001034 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001035 }
1036
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001037 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001038 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1039 return;
1040 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001041 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001042 synchronized (mBlockedAppUids) {
1043 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001044 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001045 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001046 blocked = false;
1047 } else {
1048 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001049 }
1050 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001051 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1052 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1053 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001054 }
1055
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001057 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1058 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001059 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001061 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001062 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1063
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001064 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001066 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 if (mLockdownTracker != null) {
1068 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001069 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 }
1071
1072 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 * Return NetworkInfo for the active (i.e., connected) network interface.
1074 * It is assumed that at most one network is active at a time. If more
1075 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001076 * @return the info for the active network, or {@code null} if none is
1077 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 enforceAccessPermission();
1082 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1086 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 }
1088
Paul Jensen31a94f42015-02-13 14:18:39 -05001089 @Override
1090 public Network getActiveNetwork() {
1091 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001092 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001093 }
1094
1095 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001097 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001099 }
1100
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001102 final int user = UserHandle.getUserId(uid);
1103 int vpnNetId = NETID_UNSET;
1104 synchronized (mVpns) {
1105 final Vpn vpn = mVpns.get(user);
1106 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1107 }
1108 NetworkAgentInfo nai;
1109 if (vpnNetId != NETID_UNSET) {
1110 synchronized (mNetworkForNetId) {
1111 nai = mNetworkForNetId.get(vpnNetId);
1112 }
1113 if (nai != null) return nai.network;
1114 }
1115 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 if (nai != null
1117 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1118 nai = null;
1119 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001120 return nai != null ? nai.network : null;
1121 }
1122
Lorenzo Colitti18660282016-07-04 12:55:44 +09001123 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001124 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1125 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001126 final int uid = Binder.getCallingUid();
1127 NetworkState state = getUnfilteredActiveNetworkState(uid);
1128 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001129 }
1130
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001131 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001133 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 }
1138
1139 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 public NetworkInfo getNetworkInfo(int networkType) {
1141 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001143 if (getVpnUnderlyingNetworks(uid) != null) {
1144 // A VPN is active, so we may need to return one of its underlying networks. This
1145 // information is not available in LegacyTypeTracker, so we have to get it from
1146 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001147 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001148 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001149 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001150 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001151 }
1152 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 return state.networkInfo;
1165 } else {
1166 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001168 }
1169
1170 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 public NetworkInfo[] getAllNetworkInfo() {
1172 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001173 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001174 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1175 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 NetworkInfo info = getNetworkInfo(networkType);
1177 if (info != null) {
1178 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001181 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001184 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001185 public Network getNetworkForType(int networkType) {
1186 enforceAccessPermission();
1187 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001188 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1189 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001191 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001193 }
1194
1195 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 public Network[] getAllNetworks() {
1197 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001198 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001199 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001201 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001203 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001205 }
1206
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001207 @Override
1208 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1209 // The basic principle is: if an app's traffic could possibly go over a
1210 // network, without the app doing anything multinetwork-specific,
1211 // (hence, by "default"), then include that network's capabilities in
1212 // the array.
1213 //
1214 // In the normal case, app traffic only goes over the system's default
1215 // network connection, so that's the only network returned.
1216 //
1217 // With a VPN in force, some app traffic may go into the VPN, and thus
1218 // over whatever underlying networks the VPN specifies, while other app
1219 // traffic may go over the system default network (e.g.: a split-tunnel
1220 // VPN, or an app disallowed by the VPN), so the set of networks
1221 // returned includes the VPN's underlying networks and the system
1222 // default.
1223 enforceAccessPermission();
1224
1225 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1226
1227 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001228 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001229 if (nc != null) {
1230 result.put(nai.network, nc);
1231 }
1232
1233 if (!mLockdownEnabled) {
1234 synchronized (mVpns) {
1235 Vpn vpn = mVpns.get(userId);
1236 if (vpn != null) {
1237 Network[] networks = vpn.getUnderlyingNetworks();
1238 if (networks != null) {
1239 for (Network network : networks) {
1240 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001241 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001242 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001243 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001244 }
1245 }
1246 }
1247 }
1248 }
1249 }
1250
1251 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1252 out = result.values().toArray(out);
1253 return out;
1254 }
1255
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001256 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001257 public boolean isNetworkSupported(int networkType) {
1258 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001259 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001260 }
1261
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001262 /**
1263 * Return LinkProperties for the active (i.e., connected) default
1264 * network interface. It is assumed that at most one default network
1265 * is active at a time. If more than one is active, it is indeterminate
1266 * which will be returned.
1267 * @return the ip properties for the active network, or {@code null} if
1268 * none is active
1269 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001270 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001271 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001272 enforceAccessPermission();
1273 final int uid = Binder.getCallingUid();
1274 NetworkState state = getUnfilteredActiveNetworkState(uid);
1275 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001276 }
1277
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001278 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001279 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001281 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1282 if (nai != null) {
1283 synchronized (nai) {
1284 return new LinkProperties(nai.linkProperties);
1285 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001286 }
1287 return null;
1288 }
1289
Robert Greenwalt12e67352014-05-13 21:41:06 -07001290 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001291 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001292 public LinkProperties getLinkProperties(Network network) {
1293 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001294 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1295 }
1296
1297 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1298 if (nai == null) {
1299 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001300 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001301 synchronized (nai) {
1302 return new LinkProperties(nai.linkProperties);
1303 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001304 }
1305
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001306 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001307 if (nai != null) {
1308 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001309 if (nai.networkCapabilities != null) {
1310 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001311 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001312 }
1313 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001314 return null;
1315 }
1316
1317 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001318 public NetworkCapabilities getNetworkCapabilities(Network network) {
1319 enforceAccessPermission();
1320 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1321 }
1322
1323 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001324 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001325 // Require internal since we're handing out IMSI details
1326 enforceConnectivityInternalPermission();
1327
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001328 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001329 for (Network network : getAllNetworks()) {
1330 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1331 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001332 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001333 }
1334 }
1335 return result.toArray(new NetworkState[result.size()]);
1336 }
1337
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001338 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001339 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001340 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001341 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1342 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1343 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001344 }
1345
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001346 @Override
1347 public boolean isActiveNetworkMetered() {
1348 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001349
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001350 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1351 if (caps != null) {
1352 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1353 } else {
1354 // Always return the most conservative value
1355 return true;
1356 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001357 }
1358
Jeff Sharkey216c1812012-08-05 14:29:23 -07001359 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1360 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001361 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001362 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001363 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001364 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001365 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001366
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001367 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 * Ensure that a network route exists to deliver traffic to the specified
1369 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001370 * @param networkType the type of the network over which traffic to the
1371 * specified host is to be routed
1372 * @param hostAddress the IP address of the host to which the route is
1373 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 * @return {@code true} on success, {@code false} on failure
1375 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001376 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001377 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001379 if (mProtectedNetworks.contains(networkType)) {
1380 enforceConnectivityInternalPermission();
1381 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001382
Chad Brubakerc0234532014-02-14 13:24:29 -08001383 InetAddress addr;
1384 try {
1385 addr = InetAddress.getByAddress(hostAddress);
1386 } catch (UnknownHostException e) {
1387 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1388 return false;
1389 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001392 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 return false;
1394 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001395
1396 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1397 if (nai == null) {
1398 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1399 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1400 } else {
1401 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1402 }
1403 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001404 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001405
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001406 DetailedState netState;
1407 synchronized (nai) {
1408 netState = nai.networkInfo.getDetailedState();
1409 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001410
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001411 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001412 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001413 log("requestRouteToHostAddress on down network "
1414 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001415 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001416 }
1417 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001419
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001420 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001421 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001422 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001423 LinkProperties lp;
1424 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001425 synchronized (nai) {
1426 lp = nai.linkProperties;
1427 netId = nai.network.netId;
1428 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001429 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001430 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1431 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001432 } finally {
1433 Binder.restoreCallingIdentity(token);
1434 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001435 }
1436
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001438 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001439 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001440 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001441 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001442 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001443 if (bestRoute.getGateway().equals(addr)) {
1444 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001445 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001446 } else {
1447 // if we will connect to this through another route, add a direct route
1448 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001449 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 }
1451 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001452 if (DBG) log("Adding legacy route " + bestRoute +
1453 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001454 try {
1455 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1456 } catch (Exception e) {
1457 // never crash - catch them all
1458 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 return false;
1460 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001461 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001464 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001465 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001466 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001467 // TODO: notify UID when it has requested targeted updates
1468 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001469 @Override
1470 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001471 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001472 @Override
1473 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001474 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001475 if (restrictBackground) {
1476 log("onRestrictBackgroundChanged(true): disabling tethering");
1477 mTethering.untetherAll();
1478 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001479 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001480 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001481 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001482 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001483 };
1484
Robin Lee3b3dd942015-05-12 18:14:58 +01001485 /**
1486 * Require that the caller is either in the same user or has appropriate permission to interact
1487 * across users.
1488 *
1489 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1490 */
1491 private void enforceCrossUserPermission(int userId) {
1492 if (userId == UserHandle.getCallingUserId()) {
1493 // Not a cross-user call.
1494 return;
1495 }
1496 mContext.enforceCallingOrSelfPermission(
1497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1498 "ConnectivityService");
1499 }
1500
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001501 private void enforceInternetPermission() {
1502 mContext.enforceCallingOrSelfPermission(
1503 android.Manifest.permission.INTERNET,
1504 "ConnectivityService");
1505 }
1506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.ACCESS_NETWORK_STATE,
1510 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512
1513 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001514 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
Charles Hea0a87e82017-05-15 17:07:18 +01001517 private void enforceSettingsPermission() {
1518 mContext.enforceCallingOrSelfPermission(
1519 android.Manifest.permission.NETWORK_SETTINGS,
1520 "ConnectivityService");
1521 }
1522
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001523 private void enforceTetherAccessPermission() {
1524 mContext.enforceCallingOrSelfPermission(
1525 android.Manifest.permission.ACCESS_NETWORK_STATE,
1526 "ConnectivityService");
1527 }
1528
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001529 private void enforceConnectivityInternalPermission() {
1530 mContext.enforceCallingOrSelfPermission(
1531 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1532 "ConnectivityService");
1533 }
1534
Hugo Benichi514da602016-07-19 15:59:27 +09001535 private void enforceConnectivityRestrictedNetworksPermission() {
1536 try {
1537 mContext.enforceCallingOrSelfPermission(
1538 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1539 "ConnectivityService");
1540 return;
1541 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1542 enforceConnectivityInternalPermission();
1543 }
1544
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001545 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001546 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001547 }
1548
Lorenzo Colitti18660282016-07-04 12:55:44 +09001549 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001550 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001551 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001552 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001553 }
1554
1555 private void sendInetConditionBroadcast(NetworkInfo info) {
1556 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1557 }
1558
Wink Saville628b0852011-08-04 15:01:58 -07001559 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001560 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001561 info = new NetworkInfo(info);
1562 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001563 }
1564
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001565 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001566 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001567 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 if (info.isFailover()) {
1569 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1570 info.setFailover(false);
1571 }
1572 if (info.getReason() != null) {
1573 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1574 }
1575 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001576 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1577 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001579 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001580 return intent;
1581 }
1582
1583 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1584 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1585 }
1586
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001587 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001588 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1589 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1590 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001591 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001592 final long ident = Binder.clearCallingIdentity();
1593 try {
1594 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1595 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1596 } finally {
1597 Binder.restoreCallingIdentity(ident);
1598 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001599 }
1600
Mike Lockwood0f79b542009-08-14 14:18:49 -04001601 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001602 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001603 if (!mSystemReady) {
1604 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001605 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001606 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001607 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001608 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001609 }
1610
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001611 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001612 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001613 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001614 final NetworkInfo ni = intent.getParcelableExtra(
1615 ConnectivityManager.EXTRA_NETWORK_INFO);
1616 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1617 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001619 } else {
1620 BroadcastOptions opts = BroadcastOptions.makeBasic();
1621 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1622 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001623 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001624 final IBatteryStats bs = BatteryStatsService.getService();
1625 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001626 bs.noteConnectivityChanged(intent.getIntExtra(
1627 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1628 ni != null ? ni.getState().toString() : "?");
1629 } catch (RemoteException e) {
1630 }
1631 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001632 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001633 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001634 } finally {
1635 Binder.restoreCallingIdentity(ident);
1636 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001637 }
1638 }
1639
1640 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001641 loadGlobalProxy();
1642
Hugo Benichi20035e02017-04-26 14:53:28 +09001643 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001644 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001645 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001646 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001647 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001648 }
1649 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001650 // load the global proxy at startup
1651 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001652
Robin Lee244ce8e2016-01-05 18:03:46 +00001653 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1654 // for user to unlock device too.
1655 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001656
Erik Klineda4bfa82015-04-30 12:58:40 +09001657 // Configure whether mobile data is always on.
1658 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1659
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001661
1662 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001667 *
1668 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001669 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001670 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001671 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1672 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001673
1674 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001676
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 if (networkAgent.networkCapabilities.hasTransport(
1678 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001679 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1680 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001681 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001682 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001683 } else if (networkAgent.networkCapabilities.hasTransport(
1684 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001685 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1686 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001687 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001688 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001689 } else {
1690 // do not track any other networks
1691 timeout = 0;
1692 }
1693
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001695 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001696 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001697 } catch (Exception e) {
1698 // You shall not crash!
1699 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001700 }
1701 }
1702 }
1703
1704 /**
1705 * Remove data activity tracking when network disconnects.
1706 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001707 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1708 final String iface = networkAgent.linkProperties.getInterfaceName();
1709 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001710
Robert Greenwalt7b816022014-04-18 15:25:25 -07001711 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1712 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001713 try {
1714 // the call fails silently if no idletimer setup for this interface
1715 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001716 } catch (Exception e) {
1717 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001718 }
1719 }
1720 }
1721
1722 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001723 * Reads the network specific MTU size from reources.
1724 * and set it on it's iface.
1725 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1727 final String iface = newLp.getInterfaceName();
1728 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001729 if (oldLp == null && mtu == 0) {
1730 // Silently ignore unset MTU value.
1731 return;
1732 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1734 if (VDBG) log("identical MTU - not setting");
1735 return;
1736 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001737 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001738 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 return;
1740 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001741
w1997615afd812014-08-05 15:18:11 -07001742 // Cannot set MTU without interface name
1743 if (TextUtils.isEmpty(iface)) {
1744 loge("Setting MTU size with null iface.");
1745 return;
1746 }
1747
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001749 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 mNetd.setMtu(iface, mtu);
1751 } catch (Exception e) {
1752 Slog.e(TAG, "exception in setMtu()" + e);
1753 }
1754 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001755
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001756 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001757 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1758
1759 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001760 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001761 protected MockableSystemProperties getSystemProperties() {
1762 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001763 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001764
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001765 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1766 if (isDefaultNetwork(nai) == false) {
1767 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001768 }
1769
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001770 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1771 String[] values = null;
1772 if (tcpBufferSizes != null) {
1773 values = tcpBufferSizes.split(",");
1774 }
1775
1776 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001777 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001778 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1779 values = tcpBufferSizes.split(",");
1780 }
1781
1782 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1783
1784 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001785 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001786
1787 final String prefix = "/sys/kernel/ipv4/tcp_";
1788 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1789 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1790 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1791 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1792 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1793 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1794 mCurrentTcpBufferSizes = tcpBufferSizes;
1795 } catch (IOException e) {
1796 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001797 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001798
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001799 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001800 Settings.Global.TCP_DEFAULT_INIT_RWND,
1801 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001802 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1803 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001804 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001805 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001806 }
1807
Robert Greenwalt562cc542014-05-15 18:07:26 -07001808 @Override
1809 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001810 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001811 NETWORK_RESTORE_DELAY_PROP_NAME);
1812 if(restoreDefaultNetworkDelayStr != null &&
1813 restoreDefaultNetworkDelayStr.length() != 0) {
1814 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001815 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001816 } catch (NumberFormatException e) {
1817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001819 // if the system property isn't set, use the value for the apn type
1820 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1821
1822 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1823 (mNetConfigs[networkType] != null)) {
1824 ret = mNetConfigs[networkType].restoreTime;
1825 }
1826 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
1828
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001829 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001830 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001831 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001832 }
1833 return false;
1834 }
1835
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001836 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1837 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1838 final long DIAG_TIME_MS = 5000;
1839 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1840 // Start gathering diagnostic information.
1841 netDiags.add(new NetworkDiagnostics(
1842 nai.network,
1843 new LinkProperties(nai.linkProperties), // Must be a copy.
1844 DIAG_TIME_MS));
1845 }
1846
1847 for (NetworkDiagnostics netDiag : netDiags) {
1848 pw.println();
1849 netDiag.waitForMeasurements();
1850 netDiag.dump(pw);
1851 }
1852 }
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001855 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1856 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001857 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001858
Erik Kline7747fd42017-05-12 16:52:48 +09001859 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001860 dumpNetworkDiagnostics(pw);
1861 return;
Erik Klineee363c42017-05-29 09:11:03 +09001862 } else if (argsContain(args, TETHERING_ARG)) {
1863 mTethering.dump(fd, pw, args);
1864 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001865 }
Erik Kline379747a2015-06-05 17:47:34 +09001866
Lorenzo Colittie3805462015-06-03 11:18:24 +09001867 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001868 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001869 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001870 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001871 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001872 pw.println();
1873
Paul Jensen85cf78e2015-06-25 13:25:07 -04001874 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001875 pw.print("Active default network: ");
1876 if (defaultNai == null) {
1877 pw.println("none");
1878 } else {
1879 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001881 pw.println();
1882
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001883 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001884 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001885 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1886 pw.println(nai.toString());
1887 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001888 pw.println(String.format(
1889 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1890 nai.numForegroundNetworkRequests(),
1891 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1892 nai.numBackgroundNetworkRequests(),
1893 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001894 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001895 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1896 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001897 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 pw.decreaseIndent();
1899 pw.println("Lingered:");
1900 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001901 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001902 pw.decreaseIndent();
1903 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001904 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001905 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001906 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001907
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001908 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001909 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001910 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1911 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001912 }
1913 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001914 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001915
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001916 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001917
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001918 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001919 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001920
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001921 pw.println();
1922 mKeepaliveTracker.dump(pw);
1923
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001924 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001925 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001926
Erik Kline7747fd42017-05-12 16:52:48 +09001927 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001928 pw.println();
1929 synchronized (mValidationLogs) {
1930 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001931 for (ValidationLog p : mValidationLogs) {
1932 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001933 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001934 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001935 pw.decreaseIndent();
1936 }
1937 }
Erik Kline7523eb32015-07-09 18:24:03 +09001938
1939 pw.println();
1940 pw.println("mNetworkRequestInfoLogs (most recent first):");
1941 pw.increaseIndent();
1942 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1943 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001944
1945 pw.println();
1946 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1947 pw.increaseIndent();
1948 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1949 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001950
1951 pw.println();
1952 pw.println("NetTransition WakeLock activity (most recent first):");
1953 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001954 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1955 pw.println("total releases: " + mTotalWakelockReleases);
1956 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1957 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1958 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1959 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1960 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1961 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001962 mWakelockLogs.reverseDump(fd, pw, args);
1963 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001967 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001968 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001969 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001970 if (officialNai != null && officialNai.equals(nai)) return true;
1971 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001972 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001973 " - " + nai);
1974 }
1975 return false;
1976 }
1977
Robert Greenwalt42acef32009-08-12 16:08:25 -07001978 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001979 private class NetworkStateTrackerHandler extends Handler {
1980 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001981 super(looper);
1982 }
1983
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001984 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001986 default:
1987 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001988 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001989 handleAsyncChannelHalfConnect(msg);
1990 break;
1991 }
1992 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1993 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1994 if (nai != null) nai.asyncChannel.disconnect();
1995 break;
1996 }
1997 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1998 handleAsyncChannelDisconnected(msg);
1999 break;
2000 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002001 }
2002 return true;
2003 }
2004
2005 private void maybeHandleNetworkAgentMessage(Message msg) {
2006 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2007 if (nai == null) {
2008 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002009 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 }
2011 return;
2012 }
2013
2014 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002015 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002016 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2017 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002018 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2019 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002020 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002021 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002022 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002023 break;
2024 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002025 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002026 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 break;
2028 }
2029 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 updateNetworkInfo(nai, info);
2032 break;
2033 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002034 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002035 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002036 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002037 break;
2038 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002039 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002040 try {
2041 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002042 } catch (Exception e) {
2043 // Never crash!
2044 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002045 }
2046 break;
2047 }
2048 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002049 try {
2050 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002051 } catch (Exception e) {
2052 // Never crash!
2053 loge("Exception in removeVpnUidRanges: " + e);
2054 }
2055 break;
2056 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002057 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002058 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2059 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002060 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002061 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002062 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002063 break;
2064 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002065 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002066 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2067 break;
2068 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002069 }
2070 }
2071
2072 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2073 switch (msg.what) {
2074 default:
2075 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002076 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002077 final NetworkAgentInfo nai;
2078 synchronized (mNetworkForNetId) {
2079 nai = mNetworkForNetId.get(msg.arg2);
2080 }
2081 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002082 final boolean valid =
2083 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002084 final boolean wasValidated = nai.lastValidated;
Hugo Benichi380a0632017-10-20 09:25:29 +09002085 final boolean wasDefault = isDefaultNetwork(nai);
Paul Jensen232437312016-04-06 09:51:26 -04002086 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2087 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002088 if (valid != nai.lastValidated) {
Hugo Benichi380a0632017-10-20 09:25:29 +09002089 if (wasDefault) {
2090 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2091 SystemClock.elapsedRealtime(), valid);
2092 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04002093 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002094 nai.lastValidated = valid;
2095 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002096 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002097 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2098 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002099 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002100 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002101 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002102 Bundle redirectUrlBundle = new Bundle();
2103 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002104 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002105 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002106 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002107 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002108 if (wasValidated && !nai.lastValidated) {
2109 handleNetworkUnvalidated(nai);
2110 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002111 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 break;
2113 }
Paul Jensen869868be2014-05-15 10:33:05 -04002114 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002115 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002116 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002117 final NetworkAgentInfo nai;
2118 synchronized (mNetworkForNetId) {
2119 nai = mNetworkForNetId.get(netId);
2120 }
Calvin Onbe96da12016-10-11 15:10:46 -07002121 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002122 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002123 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002124 nai.lastCaptivePortalDetected = visible;
2125 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002126 if (nai.lastCaptivePortalDetected &&
2127 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2128 if (DBG) log("Avoiding captive portal network: " + nai.name());
2129 nai.asyncChannel.sendMessage(
2130 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2131 teardownUnneededNetwork(nai);
2132 break;
2133 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002134 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002135 }
2136 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002137 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002138 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002139 if (nai == null) {
2140 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2141 break;
2142 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002143 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002144 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002145 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002146 }
Paul Jensen869868be2014-05-15 10:33:05 -04002147 }
Paul Jensen869868be2014-05-15 10:33:05 -04002148 break;
2149 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002150 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002151 return true;
2152 }
2153
Calvin Onbe96da12016-10-11 15:10:46 -07002154 private int getCaptivePortalMode() {
2155 return Settings.Global.getInt(mContext.getContentResolver(),
2156 Settings.Global.CAPTIVE_PORTAL_MODE,
2157 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2158 }
2159
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002160 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2161 switch (msg.what) {
2162 default:
2163 return false;
2164 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2165 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2166 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2167 handleLingerComplete(nai);
2168 }
2169 break;
2170 }
2171 }
2172 return true;
2173 }
2174
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 @Override
2176 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002177 if (!maybeHandleAsyncChannelMessage(msg) &&
2178 !maybeHandleNetworkMonitorMessage(msg) &&
2179 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002180 maybeHandleNetworkAgentMessage(msg);
2181 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002182 }
2183 }
2184
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002185 private void updateLingerState(NetworkAgentInfo nai, long now) {
2186 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2187 // 2. If the network was lingering and there are now requests, unlinger it.
2188 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2189 // one lingered request, start lingering.
2190 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002191 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002192 if (DBG) log("Unlingering " + nai.name());
2193 nai.unlinger();
2194 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002195 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002196 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002197 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002198 nai.linger();
2199 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2200 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2201 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002202 }
2203
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 private void handleAsyncChannelHalfConnect(Message msg) {
2205 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002206 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002207 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2208 if (VDBG) log("NetworkFactory connected");
2209 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002210 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002211 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002212 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002213 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002214 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 }
2216 } else {
2217 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002218 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002219 }
2220 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2221 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2222 if (VDBG) log("NetworkAgent connected");
2223 // A network agent has requested a connection. Establish the connection.
2224 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2225 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2226 } else {
2227 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002228 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002229 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002230 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002231 synchronized (mNetworkForNetId) {
2232 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002233 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002234 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002235 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002236 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002237 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 }
2239 }
2240 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002241
Robert Greenwalt7b816022014-04-18 15:25:25 -07002242 private void handleAsyncChannelDisconnected(Message msg) {
2243 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2244 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002245 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002246 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002247 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002249 // TODO - if we move the logic to the network agent (have them disconnect
2250 // because they lost all their requests or because their score isn't good)
2251 // then they would disconnect organically, report their new state and then
2252 // disconnect the channel.
2253 if (nai.networkInfo.isConnected()) {
2254 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2255 null, null);
2256 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002257 final boolean wasDefault = isDefaultNetwork(nai);
2258 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002259 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002260 // Log default network disconnection before required book-keeping.
2261 // Let rematchAllNetworksAndRequests() below record a new default network event
2262 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2263 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002264 long now = SystemClock.elapsedRealtime();
2265 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002266 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002267 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002268 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2269 // by other networks that are already connected. Perhaps that can be done by
2270 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2271 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002273 mKeepaliveTracker.handleStopAllKeepalives(nai,
2274 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002275 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2276 // Disable wakeup packet monitoring for each interface.
2277 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2278 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002279 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002280 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002281 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002282 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002283 // Remove the NetworkAgent, but don't mark the netId as
2284 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002285 mNetworkForNetId.remove(nai.network.netId);
2286 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002287 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002288 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2289 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002290 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002291 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002292 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002293 sendUpdatedScoreToFactories(request, 0);
2294 }
2295 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002297 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002298 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002299 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002300 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002301 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002302 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002303 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002304 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002305 if (nai.created) {
2306 // Tell netd to clean up the configuration for this network
2307 // (routing rules, DNS, etc).
2308 // This may be slow as it requires a lot of netd shelling out to ip and
2309 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2310 // after we've rematched networks with requests which should make a potential
2311 // fallback network the default or requested a new network from the
2312 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2313 // long time.
2314 try {
2315 mNetd.removeNetwork(nai.network.netId);
2316 } catch (Exception e) {
2317 loge("Exception removing network: " + e);
2318 }
2319 }
2320 synchronized (mNetworkForNetId) {
2321 mNetIdInUse.delete(nai.network.netId);
2322 }
2323 } else {
2324 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2325 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 }
2328
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002329 // If this method proves to be too slow then we can maintain a separate
2330 // pendingIntent => NetworkRequestInfo map.
2331 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2332 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2333 Intent intent = pendingIntent.getIntent();
2334 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2335 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2336 if (existingPendingIntent != null &&
2337 existingPendingIntent.getIntent().filterEquals(intent)) {
2338 return entry.getValue();
2339 }
2340 }
2341 return null;
2342 }
2343
2344 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2345 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2346
2347 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2348 if (existingRequest != null) { // remove the existing request.
2349 if (DBG) log("Replacing " + existingRequest.request + " with "
2350 + nri.request + " because their intents matched.");
2351 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2352 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002353 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002354 }
2355
Erik Klineda4bfa82015-04-30 12:58:40 +09002356 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002357 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002358 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002359 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002360 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002361 if (nri.request.networkCapabilities.hasSignalStrength() &&
2362 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2363 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002364 }
2365 }
2366 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002367 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002368 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002369 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 }
2371 }
2372
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002373 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2374 int callingUid) {
2375 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2376 if (nri != null) {
2377 handleReleaseNetworkRequest(nri.request, callingUid);
2378 }
2379 }
2380
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002381 // Determines whether the network is the best (or could become the best, if it validated), for
2382 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2383 // on the value of reason:
2384 //
2385 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2386 // then it should be torn down.
2387 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2388 // then it should be lingered.
2389 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2390 final int numRequests;
2391 switch (reason) {
2392 case TEARDOWN:
2393 numRequests = nai.numRequestNetworkRequests();
2394 break;
2395 case LINGER:
2396 numRequests = nai.numForegroundNetworkRequests();
2397 break;
2398 default:
2399 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2400 return true;
2401 }
2402
2403 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002404 return false;
2405 }
Paul Jensene0988542015-06-25 15:30:08 -04002406 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002407 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2408 // Background requests don't affect lingering.
2409 continue;
2410 }
2411
Paul Jensene0988542015-06-25 15:30:08 -04002412 // If this Network is already the highest scoring Network for a request, or if
2413 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002414 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002415 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002416 // Note that this catches two important cases:
2417 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2418 // is currently satisfying the request. This is desirable when
2419 // cellular ends up validating but WiFi does not.
2420 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002421 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002422 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002423 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002424 nai.getCurrentScoreAsValidated())) {
2425 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002426 }
2427 }
Paul Jensene0988542015-06-25 15:30:08 -04002428 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002429 }
2430
Erik Klineacdd6392016-07-07 16:50:58 +09002431 private NetworkRequestInfo getNriForAppRequest(
2432 NetworkRequest request, int callingUid, String requestedOperation) {
2433 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2434
Robert Greenwalt9258c642014-03-26 16:47:06 -07002435 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002436 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002437 log(String.format("UID %d attempted to %s for unowned request %s",
2438 callingUid, requestedOperation, nri));
2439 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002440 }
Erik Klineacdd6392016-07-07 16:50:58 +09002441 }
2442
2443 return nri;
2444 }
2445
Erik Kline57faba92015-11-25 12:49:38 +09002446 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002447 if (mNetworkRequests.get(nri.request) == null) {
2448 return;
Erik Kline57faba92015-11-25 12:49:38 +09002449 }
Hugo Benichicd952782017-09-20 11:20:14 +09002450 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002451 return;
2452 }
2453 if (VDBG || (DBG && nri.request.isRequest())) {
2454 log("releasing " + nri.request + " (timeout)");
2455 }
2456 handleRemoveNetworkRequest(nri);
2457 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002458 }
2459
Erik Klineacdd6392016-07-07 16:50:58 +09002460 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002461 final NetworkRequestInfo nri =
2462 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2463 if (nri == null) {
2464 return;
Erik Kline57faba92015-11-25 12:49:38 +09002465 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002466 if (VDBG || (DBG && nri.request.isRequest())) {
2467 log("releasing " + nri.request + " (release request)");
2468 }
2469 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002470 }
Erik Klineacdd6392016-07-07 16:50:58 +09002471
Hugo Benichidba33db2017-03-23 22:40:44 +09002472 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002473 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002474 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002475 synchronized (mUidToNetworkRequestCount) {
2476 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2477 if (requests < 1) {
2478 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2479 nri.mUid);
2480 } else if (requests == 1) {
2481 mUidToNetworkRequestCount.removeAt(
2482 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2483 } else {
2484 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2485 }
2486 }
2487 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2488 if (nri.request.isRequest()) {
2489 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002490 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002491 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002492 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002493 nai.removeRequest(nri.request.requestId);
2494 if (VDBG) {
2495 log(" Removing from current network " + nai.name() +
2496 ", leaving " + nai.numNetworkRequests() + " requests.");
2497 }
2498 // If there are still lingered requests on this network, don't tear it down,
2499 // but resume lingering instead.
2500 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002501 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002502 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2503 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002504 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002505 wasKept = true;
2506 }
Hugo Benichicd952782017-09-20 11:20:14 +09002507 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002508 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2509 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002510 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002511 }
Erik Klineacdd6392016-07-07 16:50:58 +09002512 }
2513
2514 // TODO: remove this code once we know that the Slog.wtf is never hit.
2515 //
2516 // Find all networks that are satisfying this request and remove the request
2517 // from their request lists.
2518 // TODO - it's my understanding that for a request there is only a single
2519 // network satisfying it, so this loop is wasteful
2520 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2521 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2522 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2523 otherNai.name() + ", but mNetworkAgentInfos says " +
2524 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002525 }
2526 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002527
Erik Klineacdd6392016-07-07 16:50:58 +09002528 // Maintain the illusion. When this request arrived, we might have pretended
2529 // that a network connected to serve it, even though the network was already
2530 // connected. Now that this request has gone away, we might have to pretend
2531 // that the network disconnected. LegacyTypeTracker will generate that
2532 // phantom disconnect for this type.
2533 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2534 boolean doRemove = true;
2535 if (wasKept) {
2536 // check if any of the remaining requests for this network are for the
2537 // same legacy type - if so, don't remove the nai
2538 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2539 NetworkRequest otherRequest = nai.requestAt(i);
2540 if (otherRequest.legacyType == nri.request.legacyType &&
2541 otherRequest.isRequest()) {
2542 if (DBG) log(" still have other legacy request - leaving");
2543 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002544 }
2545 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002546 }
2547
Erik Klineacdd6392016-07-07 16:50:58 +09002548 if (doRemove) {
2549 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002550 }
2551 }
Erik Klineacdd6392016-07-07 16:50:58 +09002552
2553 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2554 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2555 nri.request);
2556 }
2557 } else {
2558 // listens don't have a singular affectedNetwork. Check all networks to see
2559 // if this listen request applies and remove it.
2560 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2561 nai.removeRequest(nri.request.requestId);
2562 if (nri.request.networkCapabilities.hasSignalStrength() &&
2563 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2564 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2565 }
2566 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002567 }
2568 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002569
Lorenzo Colitti18660282016-07-04 12:55:44 +09002570 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002571 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2572 enforceConnectivityInternalPermission();
2573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002574 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002575 }
2576
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002577 @Override
2578 public void setAvoidUnvalidated(Network network) {
2579 enforceConnectivityInternalPermission();
2580 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2581 }
2582
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002583 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2584 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2585 " accept=" + accept + " always=" + always);
2586
2587 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2588 if (nai == null) {
2589 // Nothing to do.
2590 return;
2591 }
2592
2593 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002594 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002595 return;
2596 }
2597
2598 if (!nai.networkMisc.explicitlySelected) {
2599 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2600 }
2601
2602 if (accept != nai.networkMisc.acceptUnvalidated) {
2603 int oldScore = nai.getCurrentScore();
2604 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002605 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002606 sendUpdatedScoreToFactories(nai);
2607 }
2608
2609 if (always) {
2610 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002611 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002612 }
2613
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002614 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002615 // Tell the NetworkAgent to not automatically reconnect to the network.
2616 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2617 // Teardown the nework.
2618 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002619 }
2620
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002621 }
2622
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002623 private void handleSetAvoidUnvalidated(Network network) {
2624 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2625 if (nai == null || nai.lastValidated) {
2626 // Nothing to do. The network either disconnected or revalidated.
2627 return;
2628 }
2629 if (!nai.avoidUnvalidated) {
2630 int oldScore = nai.getCurrentScore();
2631 nai.avoidUnvalidated = true;
2632 rematchAllNetworksAndRequests(nai, oldScore);
2633 sendUpdatedScoreToFactories(nai);
2634 }
2635 }
2636
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002637 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002638 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002639 mHandler.sendMessageDelayed(
2640 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2641 PROMPT_UNVALIDATED_DELAY_MS);
2642 }
2643
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002644 @Override
2645 public void startCaptivePortalApp(Network network) {
2646 enforceConnectivityInternalPermission();
2647 mHandler.post(() -> {
2648 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2649 if (nai == null) return;
2650 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2651 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2652 });
2653 }
2654
Hugo Benichic8e9e122016-09-14 23:23:08 +00002655 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002656 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002657 }
2658
Erik Kline065ab6e2016-10-02 18:02:14 +09002659 private void rematchForAvoidBadWifiUpdate() {
2660 rematchAllNetworksAndRequests(null, 0);
2661 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2662 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2663 sendUpdatedScoreToFactories(nai);
2664 }
2665 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002666 }
2667
Erik Kline065ab6e2016-10-02 18:02:14 +09002668 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002669 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002670 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002671 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002672 if (!configRestrict) {
2673 pw.println("Bad Wi-Fi avoidance: unrestricted");
2674 return;
2675 }
2676
2677 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2678 pw.increaseIndent();
2679 pw.println("Config restrict: " + configRestrict);
2680
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002681 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002682 String description;
2683 // Can't use a switch statement because strings are legal case labels, but null is not.
2684 if ("0".equals(value)) {
2685 description = "get stuck";
2686 } else if (value == null) {
2687 description = "prompt";
2688 } else if ("1".equals(value)) {
2689 description = "avoid";
2690 } else {
2691 description = value + " (?)";
2692 }
2693 pw.println("User setting: " + description);
2694 pw.println("Network overrides:");
2695 pw.increaseIndent();
2696 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2697 if (nai.avoidUnvalidated) {
2698 pw.println(nai.name());
2699 }
2700 }
2701 pw.decreaseIndent();
2702 pw.decreaseIndent();
2703 }
2704
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002705 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2706 final String action;
2707 switch (type) {
2708 case NO_INTERNET:
2709 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2710 break;
2711 case LOST_INTERNET:
2712 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2713 break;
2714 default:
2715 Slog.wtf(TAG, "Unknown notification type " + type);
2716 return;
2717 }
2718
2719 Intent intent = new Intent(action);
2720 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2721 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2722 intent.setClassName("com.android.settings",
2723 "com.android.settings.wifi.WifiNoInternetDialog");
2724
2725 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2726 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2727 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2728 }
2729
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002731 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002732 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2733
2734 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2735 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002736 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002737 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002738 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2739 return;
2740 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002741 showValidationNotification(nai, NotificationType.NO_INTERNET);
2742 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002743
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002744 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2745 NetworkCapabilities nc = nai.networkCapabilities;
2746 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002747
Erik Kline065ab6e2016-10-02 18:02:14 +09002748 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002749 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002750 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2751 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002752 }
2753
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002754 @Override
2755 public int getMultipathPreference(Network network) {
2756 enforceAccessPermission();
2757
2758 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002759 if (nai != null && nai.networkCapabilities
2760 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002761 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2762 }
2763
2764 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2765 }
2766
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002767 private class InternalHandler extends Handler {
2768 public InternalHandler(Looper looper) {
2769 super(looper);
2770 }
2771
2772 @Override
2773 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002774 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002775 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002776 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002777 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002778 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002779 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002780 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002781 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002782 break;
2783 }
Jason Monkdecd2952013-10-10 14:02:51 -04002784 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002785 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002786 break;
2787 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002788 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002789 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2790 break;
2791 }
2792 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2793 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002794 break;
2795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002796 case EVENT_REGISTER_NETWORK_AGENT: {
2797 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2798 break;
2799 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002800 case EVENT_REGISTER_NETWORK_REQUEST:
2801 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002802 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002803 break;
2804 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002805 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2806 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002807 handleRegisterNetworkRequestWithIntent(msg);
2808 break;
2809 }
Erik Kline57faba92015-11-25 12:49:38 +09002810 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2811 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2812 handleTimedOutNetworkRequest(nri);
2813 break;
2814 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002815 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2816 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2817 break;
2818 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002819 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002820 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002821 break;
2822 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002823 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002824 Network network = (Network) msg.obj;
2825 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002826 break;
2827 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002828 case EVENT_SET_AVOID_UNVALIDATED: {
2829 handleSetAvoidUnvalidated((Network) msg.obj);
2830 break;
2831 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832 case EVENT_PROMPT_UNVALIDATED: {
2833 handlePromptUnvalidated((Network) msg.obj);
2834 break;
2835 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002836 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2837 handleMobileDataAlwaysOn();
2838 break;
2839 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002840 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2841 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2842 mKeepaliveTracker.handleStartKeepalive(msg);
2843 break;
2844 }
2845 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2846 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2847 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2848 int slot = msg.arg1;
2849 int reason = msg.arg2;
2850 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2851 break;
2852 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002853 case EVENT_SYSTEM_READY: {
2854 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2855 nai.networkMonitor.systemReady = true;
2856 }
2857 break;
2858 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002859 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002860 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002861 break;
2862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864 }
2865 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002866
2867 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002868 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002869 public int tether(String iface, String callerPkg) {
2870 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002871 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002872 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002873 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002874 } else {
2875 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2876 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002877 }
2878
2879 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002880 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002881 public int untether(String iface, String callerPkg) {
2882 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002883
2884 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002885 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002886 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002887 } else {
2888 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2889 }
2890 }
2891
2892 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002893 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002894 public int getLastTetherError(String iface) {
2895 enforceTetherAccessPermission();
2896
2897 if (isTetheringSupported()) {
2898 return mTethering.getLastTetherError(iface);
2899 } else {
2900 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2901 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002902 }
2903
2904 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002905 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002906 public String[] getTetherableUsbRegexs() {
2907 enforceTetherAccessPermission();
2908 if (isTetheringSupported()) {
2909 return mTethering.getTetherableUsbRegexs();
2910 } else {
2911 return new String[0];
2912 }
2913 }
2914
Lorenzo Colitti18660282016-07-04 12:55:44 +09002915 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002916 public String[] getTetherableWifiRegexs() {
2917 enforceTetherAccessPermission();
2918 if (isTetheringSupported()) {
2919 return mTethering.getTetherableWifiRegexs();
2920 } else {
2921 return new String[0];
2922 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002923 }
2924
Lorenzo Colitti18660282016-07-04 12:55:44 +09002925 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002926 public String[] getTetherableBluetoothRegexs() {
2927 enforceTetherAccessPermission();
2928 if (isTetheringSupported()) {
2929 return mTethering.getTetherableBluetoothRegexs();
2930 } else {
2931 return new String[0];
2932 }
2933 }
2934
Lorenzo Colitti18660282016-07-04 12:55:44 +09002935 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002936 public int setUsbTethering(boolean enable, String callerPkg) {
2937 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002938 if (isTetheringSupported()) {
2939 return mTethering.setUsbTethering(enable);
2940 } else {
2941 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2942 }
2943 }
2944
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002945 // TODO - move iface listing, queries, etc to new module
2946 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002947 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002948 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002949 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002950 return mTethering.getTetherableIfaces();
2951 }
2952
Lorenzo Colitti18660282016-07-04 12:55:44 +09002953 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002954 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002955 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002956 return mTethering.getTetheredIfaces();
2957 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002958
Lorenzo Colitti18660282016-07-04 12:55:44 +09002959 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002960 public String[] getTetheringErroredIfaces() {
2961 enforceTetherAccessPermission();
2962 return mTethering.getErroredIfaces();
2963 }
2964
Lorenzo Colitti18660282016-07-04 12:55:44 +09002965 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002966 public String[] getTetheredDhcpRanges() {
2967 enforceConnectivityInternalPermission();
2968 return mTethering.getTetheredDhcpRanges();
2969 }
2970
Udam Sainic3b640c2017-06-07 12:06:28 -07002971 @Override
2972 public boolean isTetheringSupported(String callerPkg) {
2973 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
2974 return isTetheringSupported();
2975 }
2976
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002977 // if ro.tether.denied = true we default to no tethering
2978 // gservices could set the secure setting to 1 though to enable it on a build where it
2979 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07002980 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002981 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2982 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2983 Settings.Global.TETHER_SUPPORTED, defaultVal));
2984 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002985 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002986
2987 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2988 boolean adminUser = false;
2989 final long token = Binder.clearCallingIdentity();
2990 try {
2991 adminUser = mUserManager.isAdminUser();
2992 } finally {
2993 Binder.restoreCallingIdentity(token);
2994 }
2995
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002996 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002997 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002998
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002999 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003000 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3001 String callerPkg) {
3002 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003003 if (!isTetheringSupported()) {
3004 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3005 return;
3006 }
3007 mTethering.startTethering(type, receiver, showProvisioningUi);
3008 }
3009
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003010 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003011 public void stopTethering(int type, String callerPkg) {
3012 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003013 mTethering.stopTethering(type);
3014 }
3015
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003016 // Called when we lose the default network and have no replacement yet.
3017 // This will automatically be cleared after X seconds or a new default network
3018 // becomes CONNECTED, whichever happens first. The timer is started by the
3019 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003020 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003021 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003022 if (mNetTransitionWakeLock.isHeld()) {
3023 return;
3024 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003025 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003026 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3027 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003028 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003029 mWakelockLogs.log("ACQUIRE for " + forWhom);
3030 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3031 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003032 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003033
Hugo Benichi4c31b342017-03-30 23:18:10 +09003034 // Called when we gain a new default network to release the network transition wakelock in a
3035 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3036 // message is cancelled.
3037 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003038 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003039 if (!mNetTransitionWakeLock.isHeld()) {
3040 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003041 }
3042 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003043 // Cancel self timeout on wakelock hold.
3044 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3045 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3046 mHandler.sendMessageDelayed(msg, 1000);
3047 }
3048
3049 // Called when either message of ensureNetworkTransitionWakelock or
3050 // scheduleReleaseNetworkTransitionWakelock is processed.
3051 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3052 String event = eventName(eventId);
3053 synchronized (this) {
3054 if (!mNetTransitionWakeLock.isHeld()) {
3055 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3056 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3057 return;
3058 }
3059 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003060 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3061 mTotalWakelockDurationMs += lockDuration;
3062 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3063 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003064 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003065 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003066 }
3067
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003068 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003069 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003070 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003071 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003072 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003073 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003074 }
3075
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003077 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003078 enforceAccessPermission();
3079 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003080 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003081 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003082 mHandler.sendMessage(
3083 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3084 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003085
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003086 private void handleReportNetworkConnectivity(
3087 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003088 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003089 if (network == null) {
3090 nai = getDefaultNetwork();
3091 } else {
3092 nai = getNetworkAgentInfoForNetwork(network);
3093 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003094 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3095 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3096 return;
3097 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003098 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003099 if (hasConnectivity == nai.lastValidated) {
3100 return;
3101 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003102 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003103 int netid = nai.network.netId;
3104 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003105 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003106 // Validating a network that has not yet connected could result in a call to
3107 // rematchNetworkAndRequests() which is not meant to work on such networks.
3108 if (!nai.everConnected) {
3109 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003110 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003111 LinkProperties lp = getLinkProperties(nai);
3112 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3113 return;
3114 }
3115 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003116 }
3117
Paul Jensencee9b512015-05-06 07:32:40 -04003118 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003119 // this information is already available as a world read/writable jvm property
3120 // so this API change wouldn't have a benifit. It also breaks the passing
3121 // of proxy info to all the JVMs.
3122 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003123 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003124 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003125 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3126 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003127 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003128 }
3129
Lorenzo Colitti18660282016-07-04 12:55:44 +09003130 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003131 public ProxyInfo getProxyForNetwork(Network network) {
3132 if (network == null) return getDefaultProxy();
3133 final ProxyInfo globalProxy = getGlobalProxy();
3134 if (globalProxy != null) return globalProxy;
3135 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3136 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3137 // caller may not have.
3138 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3139 if (nai == null) return null;
3140 synchronized (nai) {
3141 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3142 if (proxyInfo == null) return null;
3143 return new ProxyInfo(proxyInfo);
3144 }
3145 }
3146
Paul Jensene0bef712014-12-10 15:12:18 -05003147 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3148 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3149 // proxy is null then there is no proxy in place).
3150 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3151 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3152 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3153 proxy = null;
3154 }
3155 return proxy;
3156 }
3157
3158 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3159 // better for determining if a new proxy broadcast is necessary:
3160 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3161 // avoid unnecessary broadcasts.
3162 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3163 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3164 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3165 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3166 // all set.
3167 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3168 a = canonicalizeProxyInfo(a);
3169 b = canonicalizeProxyInfo(b);
3170 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3171 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3172 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3173 }
3174
Jason Monk207900c2014-04-25 15:00:09 -04003175 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003176 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003177
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003178 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179 if (proxyProperties == mGlobalProxy) return;
3180 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3181 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3182
3183 String host = "";
3184 int port = 0;
3185 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003186 String pacFileUrl = "";
3187 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003188 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003189 if (!proxyProperties.isValid()) {
3190 if (DBG)
3191 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3192 return;
3193 }
Jason Monk207900c2014-04-25 15:00:09 -04003194 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003195 host = mGlobalProxy.getHost();
3196 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003197 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003198 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003199 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003200 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003201 } else {
3202 mGlobalProxy = null;
3203 }
3204 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003205 final long token = Binder.clearCallingIdentity();
3206 try {
3207 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3208 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3209 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3210 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003211 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003212 } finally {
3213 Binder.restoreCallingIdentity(token);
3214 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003215
Jason Monkcf0f97a2014-10-02 15:39:38 -04003216 if (mGlobalProxy == null) {
3217 proxyProperties = mDefaultProxy;
3218 }
3219 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003220 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003221 }
3222
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003223 private void loadGlobalProxy() {
3224 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003225 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3226 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3227 String exclList = Settings.Global.getString(res,
3228 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003229 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3230 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003231 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003232 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003233 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003234 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003235 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003236 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003237 if (!proxyProperties.isValid()) {
3238 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3239 return;
3240 }
3241
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003242 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003243 mGlobalProxy = proxyProperties;
3244 }
3245 }
3246 }
3247
Jason Monk207900c2014-04-25 15:00:09 -04003248 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003249 // this information is already available as a world read/writable jvm property
3250 // so this API change wouldn't have a benifit. It also breaks the passing
3251 // of proxy info to all the JVMs.
3252 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003253 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003254 return mGlobalProxy;
3255 }
3256 }
3257
Jason Monk207900c2014-04-25 15:00:09 -04003258 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003259 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003260 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003261 proxy = null;
3262 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003263 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003264 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003265 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003266 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003267 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3268 return;
3269 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003270
3271 // This call could be coming from the PacManager, containing the port of the local
3272 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3273 // global (to get the correct local port), and send a broadcast.
3274 // TODO: Switch PacManager to have its own message to send back rather than
3275 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003276 if ((mGlobalProxy != null) && (proxy != null)
3277 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003278 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3279 mGlobalProxy = proxy;
3280 sendProxyBroadcast(mGlobalProxy);
3281 return;
3282 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003283 mDefaultProxy = proxy;
3284
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003285 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003286 if (!mDefaultProxyDisabled) {
3287 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 }
3289 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 }
3291
Paul Jensene0bef712014-12-10 15:12:18 -05003292 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3293 // This method gets called when any network changes proxy, but the broadcast only ever contains
3294 // the default proxy (even if it hasn't changed).
3295 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3296 // world where an app might be bound to a non-default network.
3297 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3298 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3299 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3300
3301 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3302 sendProxyBroadcast(getDefaultProxy());
3303 }
3304 }
3305
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003307 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3308 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003309 if (!TextUtils.isEmpty(proxy)) {
3310 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003311 if (data.length == 0) {
3312 return;
3313 }
3314
Robert Greenwalt434203a2010-10-11 16:00:27 -07003315 String proxyHost = data[0];
3316 int proxyPort = 8080;
3317 if (data.length > 1) {
3318 try {
3319 proxyPort = Integer.parseInt(data[1]);
3320 } catch (NumberFormatException e) {
3321 return;
3322 }
3323 }
Jason Monk207900c2014-04-25 15:00:09 -04003324 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325 setGlobalProxy(p);
3326 }
3327 }
3328
Jason Monk207900c2014-04-25 15:00:09 -04003329 private void sendProxyBroadcast(ProxyInfo proxy) {
3330 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003331 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003332 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003333 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003334 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3335 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003336 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003337 final long ident = Binder.clearCallingIdentity();
3338 try {
3339 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 }
3344
3345 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003346 final private HashMap<Uri, Integer> mUriEventMap;
3347 final private Context mContext;
3348 final private Handler mHandler;
3349
3350 SettingsObserver(Context context, Handler handler) {
3351 super(null);
3352 mUriEventMap = new HashMap<Uri, Integer>();
3353 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003354 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 }
3356
Erik Klineda4bfa82015-04-30 12:58:40 +09003357 void observe(Uri uri, int what) {
3358 mUriEventMap.put(uri, what);
3359 final ContentResolver resolver = mContext.getContentResolver();
3360 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003361 }
3362
3363 @Override
3364 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003365 Slog.wtf(TAG, "Should never be reached.");
3366 }
3367
3368 @Override
3369 public void onChange(boolean selfChange, Uri uri) {
3370 final Integer what = mUriEventMap.get(uri);
3371 if (what != null) {
3372 mHandler.obtainMessage(what.intValue()).sendToTarget();
3373 } else {
3374 loge("No matching event to send for URI=" + uri);
3375 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003376 }
3377 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003378
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003379 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003380 Slog.d(TAG, s);
3381 }
3382
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003383 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003384 Slog.e(TAG, s);
3385 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003386
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003387 private static void loge(String s, Throwable t) {
3388 Slog.e(TAG, s, t);
3389 }
3390
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003391 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003392 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003393 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3394 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3395 *
3396 * @param oldPackage Package name of the application which currently controls VPN, which will
3397 * be replaced. If there is no such application, this should should either be
3398 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3399 * @param newPackage Package name of the application which should gain control of VPN, or
3400 * {@code null} to disable.
3401 * @param userId User for whom to prepare the new VPN.
3402 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003403 * @hide
3404 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003405 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003406 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3407 int userId) {
3408 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003409 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003410
Hugo Benichi20035e02017-04-26 14:53:28 +09003411 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003412 Vpn vpn = mVpns.get(userId);
3413 if (vpn != null) {
3414 return vpn.prepare(oldPackage, newPackage);
3415 } else {
3416 return false;
3417 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003418 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003419 }
3420
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003421 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003422 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3423 * This method is used by system-privileged apps.
3424 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3425 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3426 *
3427 * @param packageName The package for which authorization state should change.
3428 * @param userId User for whom {@code packageName} is installed.
3429 * @param authorized {@code true} if this app should be able to start a VPN connection without
3430 * explicit user approval, {@code false} if not.
3431 *
Jeff Davidson05542602014-08-11 14:07:27 -07003432 * @hide
3433 */
3434 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003435 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3436 enforceCrossUserPermission(userId);
3437
Hugo Benichi20035e02017-04-26 14:53:28 +09003438 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003439 Vpn vpn = mVpns.get(userId);
3440 if (vpn != null) {
3441 vpn.setPackageAuthorization(packageName, authorized);
3442 }
Jeff Davidson05542602014-08-11 14:07:27 -07003443 }
3444 }
3445
3446 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003447 * Configure a TUN interface and return its file descriptor. Parameters
3448 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003449 * and not available in ConnectivityManager. Permissions are checked in
3450 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003451 * @hide
3452 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003453 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003454 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003455 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003456 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003457 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003458 return mVpns.get(user).establish(config);
3459 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003460 }
3461
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003462 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003463 * Start legacy VPN, controlling native daemons as needed. Creates a
3464 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003465 */
3466 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003467 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003468 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003469 final LinkProperties egress = getActiveLinkProperties();
3470 if (egress == null) {
3471 throw new IllegalStateException("Missing active network connection");
3472 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003473 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003474 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003475 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3476 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003477 }
3478
3479 /**
3480 * Return the information of the ongoing legacy VPN. This method is used
3481 * by VpnSettings and not available in ConnectivityManager. Permissions
3482 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003483 */
3484 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003485 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3486 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003487
Hugo Benichi20035e02017-04-26 14:53:28 +09003488 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003489 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003490 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003491 }
3492
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003493 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003494 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3495 * and not available in ConnectivityManager.
3496 */
3497 @Override
3498 public VpnInfo[] getAllVpnInfo() {
3499 enforceConnectivityInternalPermission();
3500 if (mLockdownEnabled) {
3501 return new VpnInfo[0];
3502 }
3503
Hugo Benichi20035e02017-04-26 14:53:28 +09003504 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003505 List<VpnInfo> infoList = new ArrayList<>();
3506 for (int i = 0; i < mVpns.size(); i++) {
3507 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3508 if (info != null) {
3509 infoList.add(info);
3510 }
3511 }
3512 return infoList.toArray(new VpnInfo[infoList.size()]);
3513 }
3514 }
3515
3516 /**
3517 * @return VPN information for accounting, or null if we can't retrieve all required
3518 * information, e.g primary underlying iface.
3519 */
3520 @Nullable
3521 private VpnInfo createVpnInfo(Vpn vpn) {
3522 VpnInfo info = vpn.getVpnInfo();
3523 if (info == null) {
3524 return null;
3525 }
3526 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3527 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3528 // the underlyingNetworks list.
3529 if (underlyingNetworks == null) {
3530 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3531 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3532 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3533 }
3534 } else if (underlyingNetworks.length > 0) {
3535 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3536 if (linkProperties != null) {
3537 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3538 }
3539 }
3540 return info.primaryUnderlyingIface == null ? null : info;
3541 }
3542
3543 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003544 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3545 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003546 * Permissions are checked in Vpn class.
3547 * @hide
3548 */
3549 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003550 public VpnConfig getVpnConfig(int userId) {
3551 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003552 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003553 Vpn vpn = mVpns.get(userId);
3554 if (vpn != null) {
3555 return vpn.getVpnConfig();
3556 } else {
3557 return null;
3558 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003559 }
3560 }
3561
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003562 @Override
3563 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003564 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3565 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3566 return false;
3567 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003568
3569 // Tear down existing lockdown if profile was removed
3570 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3571 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003572 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3573 if (profileTag == null) {
3574 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3575 return false;
3576 }
3577 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003578 final VpnProfile profile = VpnProfile.decode(
3579 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003580 if (profile == null) {
3581 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3582 setLockdownTracker(null);
3583 return true;
3584 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003585 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003586 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003587 Vpn vpn = mVpns.get(user);
3588 if (vpn == null) {
3589 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3590 return false;
3591 }
3592 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003593 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003594 } else {
3595 setLockdownTracker(null);
3596 }
3597
3598 return true;
3599 }
3600
3601 /**
3602 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3603 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3604 */
3605 private void setLockdownTracker(LockdownVpnTracker tracker) {
3606 // Shutdown any existing tracker
3607 final LockdownVpnTracker existing = mLockdownTracker;
3608 mLockdownTracker = null;
3609 if (existing != null) {
3610 existing.shutdown();
3611 }
3612
Robin Leec3736bc2017-03-10 16:19:54 +00003613 if (tracker != null) {
3614 mLockdownTracker = tracker;
3615 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003616 }
3617 }
3618
3619 private void throwIfLockdownEnabled() {
3620 if (mLockdownEnabled) {
3621 throw new IllegalStateException("Unavailable in lockdown mode");
3622 }
3623 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003624
Robin Lee244ce8e2016-01-05 18:03:46 +00003625 /**
Robin Lee17e61832016-05-09 13:46:28 +01003626 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3627 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003628 *
Robin Lee17e61832016-05-09 13:46:28 +01003629 * @return {@code true} if the service was started, the service was already connected, or there
3630 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003631 */
Robin Lee17e61832016-05-09 13:46:28 +01003632 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003633 synchronized (mVpns) {
3634 Vpn vpn = mVpns.get(userId);
3635 if (vpn == null) {
3636 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3637 // exists already.
3638 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3639 return false;
3640 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003641
Robin Lee812800c2016-05-13 15:38:08 +01003642 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003643 }
3644 }
3645
3646 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003647 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3648 enforceSettingsPermission();
3649 enforceCrossUserPermission(userId);
3650
3651 synchronized (mVpns) {
3652 Vpn vpn = mVpns.get(userId);
3653 if (vpn == null) {
3654 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3655 return false;
3656 }
3657 return vpn.isAlwaysOnPackageSupported(packageName);
3658 }
3659 }
3660
3661 @Override
Robin Leedc679712016-05-03 13:23:03 +01003662 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003663 enforceConnectivityInternalPermission();
3664 enforceCrossUserPermission(userId);
3665
3666 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3667 if (LockdownVpnTracker.isEnabled()) {
3668 return false;
3669 }
3670
Robin Lee244ce8e2016-01-05 18:03:46 +00003671 synchronized (mVpns) {
3672 Vpn vpn = mVpns.get(userId);
3673 if (vpn == null) {
3674 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3675 return false;
3676 }
Robin Lee17e61832016-05-09 13:46:28 +01003677 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003678 return false;
3679 }
Robin Lee17e61832016-05-09 13:46:28 +01003680 if (!startAlwaysOnVpn(userId)) {
3681 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003682 return false;
3683 }
3684 }
3685 return true;
3686 }
3687
3688 @Override
3689 public String getAlwaysOnVpnPackage(int userId) {
3690 enforceConnectivityInternalPermission();
3691 enforceCrossUserPermission(userId);
3692
3693 synchronized (mVpns) {
3694 Vpn vpn = mVpns.get(userId);
3695 if (vpn == null) {
3696 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3697 return null;
3698 }
3699 return vpn.getAlwaysOnPackage();
3700 }
3701 }
3702
Wink Savilleab9321d2013-06-29 21:10:57 -07003703 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003704 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003705 // TODO: Remove? Any reason to trigger a provisioning check?
3706 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003707 }
3708
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003709 /** Location to an updatable file listing carrier provisioning urls.
3710 * An example:
3711 *
3712 * <?xml version="1.0" encoding="utf-8"?>
3713 * <provisioningUrls>
3714 * <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 -07003715 * </provisioningUrls>
3716 */
3717 private static final String PROVISIONING_URL_PATH =
3718 "/data/misc/radio/provisioning_urls.xml";
3719 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003720
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003721 /** XML tag for root element. */
3722 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3723 /** XML tag for individual url */
3724 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003725 /** XML attribute for mcc */
3726 private static final String ATTR_MCC = "mcc";
3727 /** XML attribute for mnc */
3728 private static final String ATTR_MNC = "mnc";
3729
Paul Jensen434dde82015-06-11 09:43:30 -04003730 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003731 FileReader fileReader = null;
3732 XmlPullParser parser = null;
3733 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003734
3735 try {
3736 fileReader = new FileReader(mProvisioningUrlFile);
3737 parser = Xml.newPullParser();
3738 parser.setInput(fileReader);
3739 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3740
3741 while (true) {
3742 XmlUtils.nextElement(parser);
3743
3744 String element = parser.getName();
3745 if (element == null) break;
3746
Paul Jensen434dde82015-06-11 09:43:30 -04003747 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003748 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3749 try {
3750 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3751 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3752 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3753 parser.next();
3754 if (parser.getEventType() == XmlPullParser.TEXT) {
3755 return parser.getText();
3756 }
3757 }
3758 }
3759 } catch (NumberFormatException e) {
3760 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3761 }
3762 }
3763 }
3764 return null;
3765 } catch (FileNotFoundException e) {
3766 loge("Carrier Provisioning Urls file not found");
3767 } catch (XmlPullParserException e) {
3768 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3769 } catch (IOException e) {
3770 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3771 } finally {
3772 if (fileReader != null) {
3773 try {
3774 fileReader.close();
3775 } catch (IOException e) {}
3776 }
3777 }
3778 return null;
3779 }
3780
Wink Saville42d4f082013-07-20 20:31:59 -07003781 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003782 public String getMobileProvisioningUrl() {
3783 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003784 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003785 if (TextUtils.isEmpty(url)) {
3786 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003787 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003788 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003789 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003790 }
Wink Saville8cf35602013-07-10 23:00:07 -07003791 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003792 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003793 String phoneNumber = mTelephonyManager.getLine1Number();
3794 if (TextUtils.isEmpty(phoneNumber)) {
3795 phoneNumber = "0000000000";
3796 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003797 url = String.format(url,
3798 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3799 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003800 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003801 }
3802
Wink Savilleab9321d2013-06-29 21:10:57 -07003803 return url;
3804 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805
Wink Saville948282b2013-08-29 08:55:16 -07003806 @Override
3807 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003808 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003809 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003810 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3811 return;
3812 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003813 final long ident = Binder.clearCallingIdentity();
3814 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003815 // Concatenate the range of types onto the range of NetIDs.
3816 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3817 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003818 } finally {
3819 Binder.restoreCallingIdentity(ident);
3820 }
Wink Saville948282b2013-08-29 08:55:16 -07003821 }
Wink Saville7788c612013-08-29 14:57:08 -07003822
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003823 @Override
3824 public void setAirplaneMode(boolean enable) {
3825 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003826 final long ident = Binder.clearCallingIdentity();
3827 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003828 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003829 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003830 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3831 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003832 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003833 } finally {
3834 Binder.restoreCallingIdentity(ident);
3835 }
3836 }
3837
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003838 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003839 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003840 Vpn userVpn = mVpns.get(userId);
3841 if (userVpn != null) {
3842 loge("Starting user already has a VPN");
3843 return;
3844 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003845 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003846 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003847 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003848 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3849 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003850 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003851 }
3852
3853 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003854 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003855 Vpn userVpn = mVpns.get(userId);
3856 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003857 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003858 return;
3859 }
Robin Lee17e61832016-05-09 13:46:28 +01003860 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003861 mVpns.delete(userId);
3862 }
3863 }
3864
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003865 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003866 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003867 final int vpnsSize = mVpns.size();
3868 for (int i = 0; i < vpnsSize; i++) {
3869 Vpn vpn = mVpns.valueAt(i);
3870 vpn.onUserAdded(userId);
3871 }
3872 }
3873 }
3874
3875 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003876 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003877 final int vpnsSize = mVpns.size();
3878 for (int i = 0; i < vpnsSize; i++) {
3879 Vpn vpn = mVpns.valueAt(i);
3880 vpn.onUserRemoved(userId);
3881 }
3882 }
3883 }
3884
Robin Lee89e7a692016-02-29 14:38:17 +00003885 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003886 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3887 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3888 updateLockdownVpn();
3889 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003890 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003891 }
3892 }
3893
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003894 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3895 @Override
3896 public void onReceive(Context context, Intent intent) {
3897 final String action = intent.getAction();
3898 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3899 if (userId == UserHandle.USER_NULL) return;
3900
Robin Lee323f29d2016-05-04 16:38:06 +01003901 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003902 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003903 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003904 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003905 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3906 onUserAdded(userId);
3907 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3908 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003909 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3910 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003911 }
3912 }
3913 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003914
Robin Lee95204e02017-01-27 11:59:22 +00003915 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3916 @Override
3917 public void onReceive(Context context, Intent intent) {
3918 // Try creating lockdown tracker, since user present usually means
3919 // unlocked keystore.
3920 updateLockdownVpn();
3921 mContext.unregisterReceiver(this);
3922 }
3923 };
3924
Robert Greenwalta67be032014-05-16 15:49:14 -07003925 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3926 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003927 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3928 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003929
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003930 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3931 // Map from UID to number of NetworkRequests that UID has filed.
3932 @GuardedBy("mUidToNetworkRequestCount")
3933 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3934
Robert Greenwalta67be032014-05-16 15:49:14 -07003935 private static class NetworkFactoryInfo {
3936 public final String name;
3937 public final Messenger messenger;
3938 public final AsyncChannel asyncChannel;
3939
3940 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3941 this.name = name;
3942 this.messenger = messenger;
3943 this.asyncChannel = asyncChannel;
3944 }
3945 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003946
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003947 private void ensureNetworkRequestHasType(NetworkRequest request) {
3948 if (request.type == NetworkRequest.Type.NONE) {
3949 throw new IllegalArgumentException(
3950 "All NetworkRequests in ConnectivityService must have a type");
3951 }
3952 }
3953
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003954 /**
3955 * Tracks info about the requester.
3956 * Also used to notice when the calling process dies so we can self-expire
3957 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003958 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003959 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003960 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003961 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 final int mPid;
3964 final int mUid;
3965 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003966
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003967 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003968 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003969 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003970 mPendingIntent = pi;
3971 messenger = null;
3972 mBinder = null;
3973 mPid = getCallingPid();
3974 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003975 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003976 }
3977
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003978 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003979 super();
3980 messenger = m;
3981 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003982 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 mBinder = binder;
3984 mPid = getCallingPid();
3985 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003986 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003987 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003988
3989 try {
3990 mBinder.linkToDeath(this, 0);
3991 } catch (RemoteException e) {
3992 binderDied();
3993 }
3994 }
3995
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003996 private void enforceRequestCountLimit() {
3997 synchronized (mUidToNetworkRequestCount) {
3998 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3999 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004000 throw new ServiceSpecificException(
4001 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004002 }
4003 mUidToNetworkRequestCount.put(mUid, networkRequests);
4004 }
4005 }
4006
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004008 if (mBinder != null) {
4009 mBinder.unlinkToDeath(this, 0);
4010 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 }
4012
4013 public void binderDied() {
4014 log("ConnectivityService NetworkRequestInfo binderDied(" +
4015 request + ", " + mBinder + ")");
4016 releaseNetworkRequest(request);
4017 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004018
4019 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004020 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004022 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 }
4024
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004025 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4026 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4027 if (badCapability != null) {
4028 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004029 }
4030 }
4031
Erik Kline9d598e12015-07-13 16:37:51 +09004032 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004033 final SortedSet<Integer> thresholds = new TreeSet();
4034 synchronized (nai) {
4035 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4036 if (nri.request.networkCapabilities.hasSignalStrength() &&
4037 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4038 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4039 }
4040 }
4041 }
Erik Kline9d598e12015-07-13 16:37:51 +09004042 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004043 }
4044
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004045 private void updateSignalStrengthThresholds(
4046 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4047 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004048 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004049 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4050
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004051 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004052 String detail;
4053 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4054 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4055 } else {
4056 detail = reason;
4057 }
4058 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4059 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4060 }
4061
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004062 nai.asyncChannel.sendMessage(
4063 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004064 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004065 }
4066
Etan Cohen859748f2017-04-03 17:42:34 -07004067 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4068 if (nc == null) {
4069 return;
4070 }
4071 NetworkSpecifier ns = nc.getNetworkSpecifier();
4072 if (ns == null) {
4073 return;
4074 }
4075 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4076 ns.assertValidFromUid(Binder.getCallingUid());
4077 }
4078
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 @Override
4080 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004081 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004082 final NetworkRequest.Type type = (networkCapabilities == null)
4083 ? NetworkRequest.Type.TRACK_DEFAULT
4084 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004085 // If the requested networkCapabilities is null, take them instead from
4086 // the default network request. This allows callers to keep track of
4087 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004088 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004089 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4090 enforceAccessPermission();
4091 } else {
4092 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4093 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004094 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4095 // of the app when the request is filed, but we never change the request if the app
4096 // changes network state. http://b/29964605
4097 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004098 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004099 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004100
Etan Cohenba07c8c2017-02-05 10:42:27 -08004101 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 throw new IllegalArgumentException("Bad timeout specified");
4103 }
Etan Cohen859748f2017-04-03 17:42:34 -07004104 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004105
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004106 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004107 nextNetworkRequestId(), type);
4108 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004109 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110
4111 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004112 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004114 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004115 }
4116 return networkRequest;
4117 }
4118
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004120 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004121 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004122 } else {
4123 enforceChangePermission();
4124 }
4125 }
4126
fenglub15e72b2015-03-20 11:29:56 -07004127 @Override
fengludb571472015-04-21 17:12:05 -07004128 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004129 enforceAccessPermission();
4130 NetworkAgentInfo nai = null;
4131 if (network == null) {
4132 return false;
4133 }
4134 synchronized (mNetworkForNetId) {
4135 nai = mNetworkForNetId.get(network.netId);
4136 }
4137 if (nai != null) {
4138 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4139 return true;
4140 }
4141 return false;
4142 }
4143
Felipe Lemeee27cab2016-06-20 16:36:29 -07004144 private boolean isSystem(int uid) {
4145 return uid < Process.FIRST_APPLICATION_UID;
4146 }
fenglub15e72b2015-03-20 11:29:56 -07004147
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004149 final int uid = Binder.getCallingUid();
4150 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004151 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004152 return;
4153 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004154 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4155 // Policy already enforced.
4156 return;
4157 }
4158 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4159 // If UID is restricted, don't allow them to bring up metered APNs.
4160 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 }
4162 }
4163
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 @Override
4165 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4166 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167 checkNotNull(operation, "PendingIntent cannot be null.");
4168 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4169 enforceNetworkRequestPermissions(networkCapabilities);
4170 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004171 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004172 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004173
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004175 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4176 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004177 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4179 nri));
4180 return networkRequest;
4181 }
4182
Jeremy Joslin79294842014-12-03 17:15:28 -08004183 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4184 mHandler.sendMessageDelayed(
4185 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4186 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4187 }
4188
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 @Override
4190 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004191 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004192 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4193 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 }
4195
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004196 // In order to implement the compatibility measure for pre-M apps that call
4197 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4198 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4199 // This ensures it has permission to do so.
4200 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4201 if (nc == null) {
4202 return false;
4203 }
4204 int[] transportTypes = nc.getTransportTypes();
4205 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4206 return false;
4207 }
4208 try {
4209 mContext.enforceCallingOrSelfPermission(
4210 android.Manifest.permission.ACCESS_WIFI_STATE,
4211 "ConnectivityService");
4212 } catch (SecurityException e) {
4213 return false;
4214 }
4215 return true;
4216 }
4217
Robert Greenwalt9258c642014-03-26 16:47:06 -07004218 @Override
4219 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4220 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004221 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4222 enforceAccessPermission();
4223 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004225 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4226 if (!ConnectivityManager.checkChangePermission(mContext)) {
4227 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4228 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4229 // onLost and onAvailable callbacks when networks move in and out of the background.
4230 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4231 // can't request networks.
4232 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4233 }
Etan Cohen859748f2017-04-03 17:42:34 -07004234 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004235
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004236 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004237 NetworkRequest.Type.LISTEN);
4238 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004239 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240
4241 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4242 return networkRequest;
4243 }
4244
4245 @Override
4246 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4247 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004248 checkNotNull(operation, "PendingIntent cannot be null.");
4249 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4250 enforceAccessPermission();
4251 }
Etan Cohen859748f2017-04-03 17:42:34 -07004252 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004253
Erik Kline7523eb32015-07-09 18:24:03 +09004254 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004255 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4256 NetworkRequest.Type.LISTEN);
4257 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004258 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004259
4260 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261 }
4262
Erik Klineacdd6392016-07-07 16:50:58 +09004263 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004264 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004265 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004266 mHandler.sendMessage(mHandler.obtainMessage(
4267 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004268 }
4269
4270 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004271 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004272 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004273 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4274 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004275 }
4276
Robert Greenwalta67be032014-05-16 15:49:14 -07004277 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004278 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004279 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4280 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4281 }
4282
4283 @Override
4284 public void unregisterNetworkFactory(Messenger messenger) {
4285 enforceConnectivityInternalPermission();
4286 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4287 }
4288
4289 private void handleUnregisterNetworkFactory(Messenger messenger) {
4290 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4291 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004292 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004293 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004294 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004295 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004296 }
4297
Robert Greenwalt7b816022014-04-18 15:25:25 -07004298 /**
4299 * NetworkAgentInfo supporting a request by requestId.
4300 * These have already been vetted (their Capabilities satisfy the request)
4301 * and the are the highest scored network available.
4302 * the are keyed off the Requests requestId.
4303 */
Hugo Benichicd952782017-09-20 11:20:14 +09004304 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4305 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004306 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4307 new SparseArray<NetworkAgentInfo>();
4308
Paul Jensen31a94f42015-02-13 14:18:39 -05004309 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4310 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4312 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004313 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4314 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4315 // there may not be a strict 1:1 correlation between the two.
4316 @GuardedBy("mNetworkForNetId")
4317 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318
Robert Greenwalt7b816022014-04-18 15:25:25 -07004319 // NetworkAgentInfo keyed off its connecting messenger
4320 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004321 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004322 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4323 new HashMap<Messenger, NetworkAgentInfo>();
4324
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004325 @GuardedBy("mBlockedAppUids")
4326 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4327
Paul Jensen2c311d62014-11-17 12:34:51 -05004328 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004329 private final NetworkRequest mDefaultRequest;
4330
Erik Klineda4bfa82015-04-30 12:58:40 +09004331 // Request used to optionally keep mobile data active even when higher
4332 // priority networks like Wi-Fi are active.
4333 private final NetworkRequest mDefaultMobileDataRequest;
4334
Hugo Benichicd952782017-09-20 11:20:14 +09004335 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4336 synchronized (mNetworkForRequestId) {
4337 return mNetworkForRequestId.get(requestId);
4338 }
4339 }
4340
4341 private void clearNetworkForRequest(int requestId) {
4342 synchronized (mNetworkForRequestId) {
4343 mNetworkForRequestId.remove(requestId);
4344 }
4345 }
4346
4347 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4348 synchronized (mNetworkForRequestId) {
4349 mNetworkForRequestId.put(requestId, nai);
4350 }
4351 }
4352
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004353 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004354 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004355 }
4356
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004357 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004358 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004359 }
4360
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004361 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4362 return nri.request.requestId == mDefaultRequest.requestId;
4363 }
4364
Paul Jensen31a94f42015-02-13 14:18:39 -05004365 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004366 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004367 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004368 enforceConnectivityInternalPermission();
4369
Rubin Xu1bb5c082017-09-05 18:40:49 +01004370 LinkProperties lp = new LinkProperties(linkProperties);
4371 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004372 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4373 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004374 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004375 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4376 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004377 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004378 synchronized (this) {
4379 nai.networkMonitor.systemReady = mSystemReady;
4380 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004381 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4382 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004383 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004385 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386 }
4387
4388 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4389 if (VDBG) log("Got NetworkAgent Messenger");
4390 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004391 synchronized (mNetworkForNetId) {
4392 mNetworkForNetId.put(na.network.netId, na);
4393 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4395 NetworkInfo networkInfo = na.networkInfo;
4396 na.networkInfo = null;
4397 updateNetworkInfo(na, networkInfo);
4398 }
4399
4400 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4401 LinkProperties newLp = networkAgent.linkProperties;
4402 int netId = networkAgent.network.netId;
4403
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004404 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4405 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004406 if (networkAgent.clatd != null) {
4407 networkAgent.clatd.fixupLinkProperties(oldLp);
4408 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004409
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004410 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 updateMtu(newLp, oldLp);
4412 // TODO - figure out what to do for clat
4413// for (LinkProperties lp : newLp.getStackedLinks()) {
4414// updateMtu(lp, null);
4415// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004416 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004417
Erik Kline94887872016-04-05 13:30:49 +09004418 updateRoutes(newLp, oldLp, netId);
4419 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004420
Hugo Benichib577d652017-06-27 15:13:20 +09004421 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004422 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004423 if (isDefaultNetwork(networkAgent)) {
4424 handleApplyDefaultProxy(newLp.getHttpProxy());
4425 } else {
4426 updateProxy(newLp, oldLp, networkAgent);
4427 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004428 // TODO - move this check to cover the whole function
4429 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004430 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004431 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4432 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004433
4434 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004435 }
4436
Joel Scherpelz668370b2017-06-08 15:35:21 +09004437 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004438 // Marks are only available on WiFi interaces. Checking for
4439 // marks on unsupported interfaces is harmless.
4440 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4441 return;
4442 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004443
Joel Scherpelz668370b2017-06-08 15:35:21 +09004444 int mark = mContext.getResources().getInteger(
4445 com.android.internal.R.integer.config_networkWakeupPacketMark);
4446 int mask = mContext.getResources().getInteger(
4447 com.android.internal.R.integer.config_networkWakeupPacketMask);
4448
4449 // Mask/mark of zero will not detect anything interesting.
4450 // Don't install rules unless both values are nonzero.
4451 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004452 return;
4453 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004454
4455 final String prefix = "iface:" + iface;
4456 try {
4457 if (add) {
4458 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4459 } else {
4460 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4461 }
4462 } catch (Exception e) {
4463 loge("Exception modifying wakeup packet monitoring: " + e);
4464 }
4465
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004466 }
4467
4468 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4469 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004470 CompareResult<String> interfaceDiff = new CompareResult<String>(
4471 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4472 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004473 for (String iface : interfaceDiff.added) {
4474 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004475 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004476 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004477 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004478 } catch (Exception e) {
4479 loge("Exception adding interface: " + e);
4480 }
4481 }
4482 for (String iface : interfaceDiff.removed) {
4483 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004484 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004485 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004486 mNetd.removeInterfaceFromNetwork(iface, netId);
4487 } catch (Exception e) {
4488 loge("Exception removing interface: " + e);
4489 }
4490 }
4491 }
4492
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004493 /**
4494 * Have netd update routes from oldLp to newLp.
4495 * @return true if routes changed between oldLp and newLp
4496 */
4497 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004498 // Compare the route diff to determine which routes should be added and removed.
4499 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4500 oldLp != null ? oldLp.getAllRoutes() : null,
4501 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004502
4503 // add routes before removing old in case it helps with continuous connectivity
4504
4505 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4506 for (RouteInfo route : routeDiff.added) {
4507 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004508 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004509 try {
4510 mNetd.addRoute(netId, route);
4511 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004512 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4513 loge("Exception in addRoute for non-gateway: " + e);
4514 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 }
4516 }
4517 for (RouteInfo route : routeDiff.added) {
4518 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004519 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 try {
4521 mNetd.addRoute(netId, route);
4522 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004523 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4524 loge("Exception in addRoute for gateway: " + e);
4525 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
4527 }
4528
4529 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004530 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 try {
4532 mNetd.removeRoute(netId, route);
4533 } catch (Exception e) {
4534 loge("Exception in removeRoute: " + e);
4535 }
4536 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004537 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 }
Erik Kline41368502015-06-17 13:19:54 +09004539
Erik Kline94887872016-04-05 13:30:49 +09004540 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4541 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4542 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 }
Erik Kline94887872016-04-05 13:30:49 +09004544
Erik Kline1742fe12017-12-13 19:40:49 +09004545 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4546 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4547
Erik Kline94887872016-04-05 13:30:49 +09004548 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004549 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004550 try {
Erik Kline1742fe12017-12-13 19:40:49 +09004551 mDnsManager.setDnsConfigurationForNetwork(
4552 netId, dnses, newLp.getDomains(), isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004553 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004554 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004555 }
Erik Kline4edba012017-04-07 15:29:29 +09004556 }
4557
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004558 private String getNetworkPermission(NetworkCapabilities nc) {
4559 // TODO: make these permission strings AIDL constants instead.
4560 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4561 return NetworkManagementService.PERMISSION_SYSTEM;
4562 }
4563 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4564 return NetworkManagementService.PERMISSION_NETWORK;
4565 }
4566 return null;
4567 }
4568
Paul Jensen3d194ea2015-06-16 14:27:36 -04004569 /**
4570 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4571 * augmented with any stateful capabilities implied from {@code networkAgent}
4572 * (e.g., validated status and captive portal status).
4573 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004574 * @param oldScore score of the network before any of the changes that prompted us
4575 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004576 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004577 * @param networkCapabilities the new network capabilities.
4578 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004579 private void updateCapabilities(
4580 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004581 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004582 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4583 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004584 // TODO: consider not complaining when a network agent degrade its capabilities if this
4585 // does not cause any request (that is not a listen) currently matching that agent to
4586 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004587 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4588 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004589 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004590 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004591 }
4592
Paul Jensen3d194ea2015-06-16 14:27:36 -04004593 // Don't modify caller's NetworkCapabilities.
4594 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004595 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004596 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4597 } else {
4598 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4599 }
Paul Jensene0988542015-06-25 15:30:08 -04004600 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004601 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4602 } else {
4603 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4604 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004605 if (nai.isBackgroundNetwork()) {
4606 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4607 } else {
4608 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4609 }
4610
4611 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4612
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004613 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4614 final String newPermission = getNetworkPermission(networkCapabilities);
4615 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004616 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004617 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004618 } catch (RemoteException e) {
4619 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004620 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004621 }
4622
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004623 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004624 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004625 prevNc = nai.networkCapabilities;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004626 nai.networkCapabilities = networkCapabilities;
4627 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004628
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004629 if (nai.getCurrentScore() == oldScore &&
4630 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4631 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4632 // the change we're processing can't affect any requests, it can only affect the listens
4633 // on this network. We might have been called by rematchNetworkAndRequests when a
4634 // network changed foreground state.
4635 processListenRequests(nai, true);
4636 } else {
4637 // If the requestable capabilities have changed or the score changed, we can't have been
4638 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004639 rematchAllNetworksAndRequests(nai, oldScore);
4640 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004641 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004642
4643 // Report changes that are interesting for network statistics tracking.
4644 if (prevNc != null) {
4645 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
4646 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED);
4647 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
4648 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING);
4649 if (meteredChanged || roamingChanged) {
4650 notifyIfacesChangedForNetworkStats();
4651 }
4652 }
4653
4654 if (!networkCapabilities.hasTransport(TRANSPORT_VPN)) {
4655 // Tell VPNs about updated capabilities, since they may need to
4656 // bubble those changes through.
4657 synchronized (mVpns) {
4658 for (int i = 0; i < mVpns.size(); i++) {
4659 final Vpn vpn = mVpns.valueAt(i);
4660 vpn.updateCapabilities();
4661 }
4662 }
4663 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004664 }
4665
Hugo Benichief502882017-09-01 01:23:32 +00004666 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4667 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4668 // Ignore updates for disconnected networks
4669 return;
4670 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004671 // newLp is already a defensive copy.
4672 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004673 if (VDBG) {
4674 log("Update of LinkProperties for " + nai.name() +
4675 "; created=" + nai.created +
4676 "; everConnected=" + nai.everConnected);
4677 }
4678 LinkProperties oldLp = nai.linkProperties;
4679 synchronized (nai) {
4680 nai.linkProperties = newLp;
4681 }
4682 if (nai.everConnected) {
4683 updateLinkProperties(nai, oldLp);
4684 }
4685 }
4686
Paul Jensenc8b9a742014-09-30 15:37:41 -04004687 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004688 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4689 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004690 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004691 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004692 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4693 }
4694 }
4695
Robert Greenwalt7b816022014-04-18 15:25:25 -07004696 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4697 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004698 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004699 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4700 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004701 }
4702 }
4703
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004704 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4705 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004706 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004707 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004708 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4709 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004710 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004711 sendIntent(nri.mPendingIntent, intent);
4712 }
4713 // else not handled
4714 }
4715
4716 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4717 mPendingIntentWakeLock.acquire();
4718 try {
4719 if (DBG) log("Sending " + pendingIntent);
4720 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4721 } catch (PendingIntent.CanceledException e) {
4722 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4723 mPendingIntentWakeLock.release();
4724 releasePendingNetworkRequest(pendingIntent);
4725 }
4726 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4727 }
4728
4729 @Override
4730 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4731 String resultData, Bundle resultExtras) {
4732 if (DBG) log("Finished sending " + pendingIntent);
4733 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004734 // Release with a delay so the receiving client has an opportunity to put in its
4735 // own request.
4736 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004737 }
4738
Hugo Benichidba33db2017-03-23 22:40:44 +09004739 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004740 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004741 if (nri.messenger == null) {
4742 return; // Default request has no msgr
4743 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004744 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004745 // TODO: check if defensive copies of data is needed.
4746 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004747 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004748 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4749 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004750 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004751 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004752 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004753 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004754 break;
4755 }
4756 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004757 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004758 break;
4759 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004761 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004762 break;
4763 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004764 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004765 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004766 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004768 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004769 String notification = ConnectivityManager.getCallbackName(notificationType);
4770 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004771 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004772 nri.messenger.send(msg);
4773 } catch (RemoteException e) {
4774 // may occur naturally in the race of binder death.
4775 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4776 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 }
4778
Hugo Benichidba33db2017-03-23 22:40:44 +09004779 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4780 bundle.putParcelable(t.getClass().getSimpleName(), t);
4781 }
4782
Paul Jensenc8b9a742014-09-30 15:37:41 -04004783 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004784 if (nai.numRequestNetworkRequests() != 0) {
4785 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4786 NetworkRequest nr = nai.requestAt(i);
4787 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004788 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004789 loge("Dead network still had at least " + nr);
4790 break;
4791 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004792 }
4793 nai.asyncChannel.disconnect();
4794 }
4795
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4797 if (oldNetwork == null) {
4798 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4799 return;
4800 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004801 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004802
4803 // If we get here it means that the last linger timeout for this network expired. So there
4804 // must be no other active linger timers, and we must stop lingering.
4805 oldNetwork.clearLingerState();
4806
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004807 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004808 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004809 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004810 } else {
4811 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004812 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4813 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004814 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004815 }
4816
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004817 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004818 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004819 setupDataActivityTracking(newNetwork);
4820 try {
4821 mNetd.setDefaultNetId(newNetwork.network.netId);
4822 } catch (Exception e) {
4823 loge("Exception setting default network :" + e);
4824 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004825 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004826 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004827 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09004828 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004829 }
4830
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004831 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004832 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4833 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4834 NetworkRequest nr = nri.request;
4835 if (!nr.isListen()) continue;
4836 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4837 nai.removeRequest(nri.request.requestId);
4838 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4839 }
4840 }
4841
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004842 if (capabilitiesChanged) {
4843 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4844 }
4845
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004846 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4847 NetworkRequest nr = nri.request;
4848 if (!nr.isListen()) continue;
4849 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4850 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004851 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004852 }
4853 }
4854 }
4855
Paul Jensen2161a8e2014-09-11 11:00:39 -04004856 // Handles a network appearing or improving its score.
4857 //
4858 // - Evaluates all current NetworkRequests that can be
4859 // satisfied by newNetwork, and reassigns to newNetwork
4860 // any such requests for which newNetwork is the best.
4861 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004862 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004863 // needed. A network is needed if it is the best network for
4864 // one or more NetworkRequests, or if it is a VPN.
4865 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004866 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004867 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004868 //
4869 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4870 // networks that have no chance (i.e. even if validated)
4871 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004872 //
4873 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4874 // it does not remove NetworkRequests that other Networks could better satisfy.
4875 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4876 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4877 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004878 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004879 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004880 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4881 // performed to tear down unvalidated networks that have no chance (i.e. even if
4882 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004883 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004884 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004885 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004886 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004887 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004888 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004889
4890 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4891 final int score = newNetwork.getCurrentScore();
4892
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004893 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004894
Paul Jensen2161a8e2014-09-11 11:00:39 -04004895 // Find and migrate to this Network any NetworkRequests for
4896 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004898 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004899 NetworkCapabilities nc = newNetwork.networkCapabilities;
4900 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004901 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004902 // Process requests in the first pass and listens in the second pass. This allows us to
4903 // change a network's capabilities depending on which requests it has. This is only
4904 // correct if the change in capabilities doesn't affect whether the network satisfies
4905 // requests or not, and doesn't affect the network's score.
4906 if (nri.request.isListen()) continue;
4907
Hugo Benichicd952782017-09-20 11:20:14 +09004908 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004909 final boolean satisfies = newNetwork.satisfies(nri.request);
4910 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004911 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004912 log("Network " + newNetwork.name() + " was already satisfying" +
4913 " request " + nri.request.requestId + ". No change.");
4914 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004915 keep = true;
4916 continue;
4917 }
4918
4919 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004920 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004921 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004922 // next check if it's better than any current network we're using for
4923 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004924 if (VDBG) {
4925 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004926 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004927 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004928 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004929 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004930 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004932 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004933 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004934 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004935 affectedNetworks.add(currentNetwork);
4936 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004937 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004939 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09004940 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004941 if (!newNetwork.addRequest(nri.request)) {
4942 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4943 }
4944 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004945 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004946 // Tell NetworkFactories about the new score, so they can stop
4947 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 // TODO - this could get expensive if we have alot of requests for this
4949 // network. Think about if there is a way to reduce this. Push
4950 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004951 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004952 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004953 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004954 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004955 if (currentNetwork != null) {
4956 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4957 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 }
4959 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004960 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004961 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4962 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004963 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004964 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4965 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4966 // This means this code doesn't have to handle the case where "currentNetwork" no
4967 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4968 if (DBG) {
4969 log("Network " + newNetwork.name() + " stopped satisfying" +
4970 " request " + nri.request.requestId);
4971 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004972 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09004974 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004975 sendUpdatedScoreToFactories(nri.request, 0);
4976 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004977 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4978 newNetwork.name() +
4979 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004980 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004981 // TODO: Technically, sending CALLBACK_LOST here is
4982 // incorrect if there is a replacement network currently
4983 // connected that can satisfy nri, which is a request
4984 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004985 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4986 // so this code is only incorrect for a network that loses
4987 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004988 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004989 }
4990 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004991 if (isNewDefault) {
4992 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004993 makeDefault(newNetwork);
4994 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09004995 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09004996 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004997 // Have a new default network, release the transition wakelock in
4998 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004999 }
5000
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005001 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5002 Slog.wtf(TAG, String.format(
5003 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005004 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005005 }
5006 if (newNetwork.getCurrentScore() != score) {
5007 Slog.wtf(TAG, String.format(
5008 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005009 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005010 }
5011
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005012 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005013 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5014 // If the network went from background to foreground or vice versa, we need to update
5015 // its foreground state. It is safe to do this after rematching the requests because
5016 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5017 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005018 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005019 } else {
5020 processListenRequests(newNetwork, false);
5021 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005022
Paul Jensencf4c2c62015-07-01 14:16:32 -04005023 // do this after the default net is switched, but
5024 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005025 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005026
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005027 // Linger any networks that are no longer needed. This should be done after sending the
5028 // available callback for newNetwork.
5029 for (NetworkAgentInfo nai : affectedNetworks) {
5030 updateLingerState(nai, now);
5031 }
5032 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5033 // does not need to be done in any particular order.
5034 updateLingerState(newNetwork, now);
5035
Paul Jensencf4c2c62015-07-01 14:16:32 -04005036 if (isNewDefault) {
5037 // Maintain the illusion: since the legacy API only
5038 // understands one network at a time, we must pretend
5039 // that the current default network disconnected before
5040 // the new one connected.
5041 if (oldDefaultNetwork != null) {
5042 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5043 oldDefaultNetwork, true);
5044 }
5045 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5046 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5047 notifyLockdownVpn(newNetwork);
5048 }
5049
Robert Greenwalt7b816022014-04-18 15:25:25 -07005050 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005051 // Notify battery stats service about this network, both the normal
5052 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005053 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005054 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005055 final IBatteryStats bs = BatteryStatsService.getService();
5056 final int type = newNetwork.networkInfo.getType();
5057
5058 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5059 bs.noteNetworkInterfaceType(baseIface, type);
5060 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5061 final String stackedIface = stacked.getInterfaceName();
5062 bs.noteNetworkInterfaceType(stackedIface, type);
5063 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5064 }
5065 } catch (RemoteException ignored) {
5066 }
5067
Robert Greenwalt152ed372014-12-17 17:19:53 -08005068 // This has to happen after the notifyNetworkCallbacks as that tickles each
5069 // ConnectivityManager instance so that legacy requests correctly bind dns
5070 // requests to this network. The legacy users are listening for this bcast
5071 // and will generally do a dns request so they can ensureRouteToHost and if
5072 // they do that before the callbacks happen they'll use the default network.
5073 //
5074 // TODO: Is there still a race here? We send the broadcast
5075 // after sending the callback, but if the app can receive the
5076 // broadcast before the callback, it might still break.
5077 //
5078 // This *does* introduce a race where if the user uses the new api
5079 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5080 // they may get old info. Reverse this after the old startUsing api is removed.
5081 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005082 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5083 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005084 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005085 // legacy type tracker filters out repeat adds
5086 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5087 }
5088 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005089
5090 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5091 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5092 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5093 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5094 if (newNetwork.isVPN()) {
5095 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5096 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005097 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005098 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5099 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005100 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005101 if (nai.getLingerExpiry() > 0) {
5102 // This network has active linger timers and no requests, but is not
5103 // lingering. Linger it.
5104 //
5105 // One way (the only way?) this can happen if this network is unvalidated
5106 // and became unneeded due to another network improving its score to the
5107 // point where this network will no longer be able to satisfy any requests
5108 // even if it validates.
5109 updateLingerState(nai, now);
5110 } else {
5111 if (DBG) log("Reaping " + nai.name());
5112 teardownUnneededNetwork(nai);
5113 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005114 }
5115 }
5116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005117 }
5118
Paul Jensen1c7ba022015-06-16 14:27:36 -04005119 /**
5120 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5121 * being disconnected.
5122 * @param changed If only one Network's score or capabilities have been modified since the last
5123 * time this function was called, pass this Network in this argument, otherwise pass
5124 * null.
5125 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5126 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5127 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5128 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5129 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005130 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005131 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005132 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5133 // to avoid the slowness. It is not simply enough to process just "changed", for
5134 // example in the case where "changed"'s score decreases and another network should begin
5135 // satifying a NetworkRequest that "changed" currently satisfies.
5136
5137 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5138 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5139 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005140 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005141 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005142 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005143 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005144 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5145 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5146 // Rematch higher scoring networks first to prevent requests first matching a lower
5147 // scoring network and then a higher scoring network, which could produce multiple
5148 // callbacks and inadvertently unlinger networks.
5149 Arrays.sort(nais);
5150 for (NetworkAgentInfo nai : nais) {
5151 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005152 // Only reap the last time through the loop. Reaping before all rematching
5153 // is complete could incorrectly teardown a network that hasn't yet been
5154 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005155 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005156 : ReapUnvalidatedNetworks.REAP,
5157 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005158 }
5159 }
5160 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005161
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005162 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005163 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005164 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005165 // For now only update icons for default connection.
5166 // TODO: Update WiFi and cellular icons separately. b/17237507
5167 if (!isDefaultNetwork(nai)) return;
5168
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005169 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005170 // Don't repeat publish.
5171 if (newInetCondition == mDefaultInetConditionPublished) return;
5172
5173 mDefaultInetConditionPublished = newInetCondition;
5174 sendInetConditionBroadcast(nai.networkInfo);
5175 }
5176
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005177 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5178 if (mLockdownTracker != null) {
5179 if (nai != null && nai.isVPN()) {
5180 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5181 } else {
5182 mLockdownTracker.onNetworkInfoChanged();
5183 }
5184 }
5185 }
5186
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005188 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005189 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005190 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005191 synchronized (networkAgent) {
5192 oldInfo = networkAgent.networkInfo;
5193 networkAgent.networkInfo = newInfo;
5194 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005195 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005196
Robert Greenwalt7b816022014-04-18 15:25:25 -07005197 if (DBG) {
5198 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5199 (oldInfo == null ? "null" : oldInfo.getState()) +
5200 " to " + state);
5201 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005202
Robin Lee585e2482016-05-01 23:00:00 +01005203 if (!networkAgent.created
5204 && (state == NetworkInfo.State.CONNECTED
5205 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005206
5207 // A network that has just connected has zero requests and is thus a foreground network.
5208 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5209
Robert Greenwalt7b816022014-04-18 15:25:25 -07005210 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005211 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005212 if (networkAgent.isVPN()) {
5213 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005214 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5215 (networkAgent.networkMisc == null ||
5216 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005217 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005218 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005219 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005220 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005221 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005222 loge("Error creating network " + networkAgent.network.netId + ": "
5223 + e.getMessage());
5224 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005225 }
Paul Jenseneec75412014-08-04 12:21:19 -04005226 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005227 }
5228
5229 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5230 networkAgent.everConnected = true;
5231
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005233 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005234
Paul Jensenca8f16a2014-05-09 12:47:55 -04005235 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005236 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005237
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005238 if (networkAgent.isVPN()) {
5239 // Temporarily disable the default proxy (not global).
5240 synchronized (mProxyLock) {
5241 if (!mDefaultProxyDisabled) {
5242 mDefaultProxyDisabled = true;
5243 if (mGlobalProxy == null && mDefaultProxy != null) {
5244 sendProxyBroadcast(null);
5245 }
5246 }
5247 }
5248 // TODO: support proxy per network.
5249 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005250
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005251 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5252 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5253 // capabilities, so it only needs to be done once on initial connect, not every time the
5254 // network's capabilities change. Note that we do this before rematching the network,
5255 // so we could decide to tear it down immediately afterwards. That's fine though - on
5256 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5257 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005258 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005259
Paul Jensen2161a8e2014-09-11 11:00:39 -04005260 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005261 final long now = SystemClock.elapsedRealtime();
5262 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005263
5264 // This has to happen after matching the requests, because callbacks are just requests.
5265 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005266 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005267 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005268 if (networkAgent.isVPN()) {
5269 synchronized (mProxyLock) {
5270 if (mDefaultProxyDisabled) {
5271 mDefaultProxyDisabled = false;
5272 if (mGlobalProxy == null && mDefaultProxy != null) {
5273 sendProxyBroadcast(mDefaultProxy);
5274 }
5275 }
5276 }
5277 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005278 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5279 state == NetworkInfo.State.SUSPENDED) {
5280 // going into or coming out of SUSPEND: rescore and notify
5281 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005282 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005283 }
5284 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5285 ConnectivityManager.CALLBACK_SUSPENDED :
5286 ConnectivityManager.CALLBACK_RESUMED));
5287 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005288 }
5289 }
5290
Robert Greenwaltac96c522014-06-03 16:43:57 -07005291 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005292 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005293 if (score < 0) {
5294 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5295 "). Bumping score to min of 0");
5296 score = 0;
5297 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005298
Paul Jensen2161a8e2014-09-11 11:00:39 -04005299 final int oldScore = nai.getCurrentScore();
5300 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005301
Paul Jensen85cf78e2015-06-25 13:25:07 -04005302 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005303
Paul Jensenc8b9a742014-09-30 15:37:41 -04005304 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005305 }
5306
Erik Klinec75d4fa2017-02-15 19:59:17 +09005307 // Notify only this one new request of the current state. Transfer all the
5308 // current state by calling NetworkCapabilities and LinkProperties callbacks
5309 // so that callers can be guaranteed to have as close to atomicity in state
5310 // transfer as can be supported by this current API.
5311 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005312 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005313 if (nri.mPendingIntent != null) {
5314 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5315 // Attempt no subsequent state pushes where intents are involved.
5316 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005317 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005318
5319 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5320 // Whether a network is currently suspended is also an important
5321 // element of state to be transferred (it would not otherwise be
5322 // delivered by any currently available mechanism).
5323 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5324 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5325 }
5326 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5327 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005328 }
5329
Robert Greenwalt8d482522015-06-24 13:23:42 -07005330 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005331 // The NetworkInfo we actually send out has no bearing on the real
5332 // state of affairs. For example, if the default connection is mobile,
5333 // and a request for HIPRI has just gone away, we need to pretend that
5334 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5335 // the state to DISCONNECTED, even though the network is of type MOBILE
5336 // and is still connected.
5337 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5338 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005339 if (state != DetailedState.DISCONNECTED) {
5340 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005341 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005342 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005343 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005344 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5345 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5346 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5347 if (info.isFailover()) {
5348 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5349 nai.networkInfo.setFailover(false);
5350 }
5351 if (info.getReason() != null) {
5352 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5353 }
5354 if (info.getExtraInfo() != null) {
5355 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5356 }
5357 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005358 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005359 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005360 if (newDefaultAgent != null) {
5361 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5362 newDefaultAgent.networkInfo);
5363 } else {
5364 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5365 }
5366 }
5367 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5368 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005369 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005370 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005371 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005372 }
5373 }
5374 }
5375
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005376 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005377 if (VDBG) {
5378 String notification = ConnectivityManager.getCallbackName(notifyType);
5379 log("notifyType " + notification + " for " + networkAgent.name());
5380 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005381 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5382 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005383 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5384 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005385 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5386 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005387 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005388 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005389 } else {
5390 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5391 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005393 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005394
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005395 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5396 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5397 }
5398
Jeff Sharkey69736342014-12-08 14:50:12 -08005399 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005400 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5401 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005402 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005403 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005404 try {
5405 mStatsService.forceUpdateIfaces();
5406 } catch (Exception ignored) {
5407 }
5408 }
5409
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005410 @Override
5411 public boolean addVpnAddress(String address, int prefixLength) {
5412 throwIfLockdownEnabled();
5413 int user = UserHandle.getUserId(Binder.getCallingUid());
5414 synchronized (mVpns) {
5415 return mVpns.get(user).addAddress(address, prefixLength);
5416 }
5417 }
5418
5419 @Override
5420 public boolean removeVpnAddress(String address, int prefixLength) {
5421 throwIfLockdownEnabled();
5422 int user = UserHandle.getUserId(Binder.getCallingUid());
5423 synchronized (mVpns) {
5424 return mVpns.get(user).removeAddress(address, prefixLength);
5425 }
5426 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005427
5428 @Override
5429 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5430 throwIfLockdownEnabled();
5431 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005432 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005433 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005434 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005435 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005436 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005437 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005438 }
5439 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005440 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005441
5442 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005443 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005444 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005445 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005446 }
5447
5448 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005449 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5450 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5451 enforceKeepalivePermission();
5452 mKeepaliveTracker.startNattKeepalive(
5453 getNetworkAgentInfoForNetwork(network),
5454 intervalSeconds, messenger, binder,
5455 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5456 }
5457
5458 @Override
5459 public void stopKeepalive(Network network, int slot) {
5460 mHandler.sendMessage(mHandler.obtainMessage(
5461 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5462 }
5463
5464 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465 public void factoryReset() {
5466 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005467
5468 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5469 return;
5470 }
5471
Robin Lee3b3dd942015-05-12 18:14:58 +01005472 final int userId = UserHandle.getCallingUserId();
5473
Stuart Scottf1fb3972015-04-02 18:00:02 -07005474 // Turn airplane mode off
5475 setAirplaneMode(false);
5476
Stuart Scotte3e314d2015-04-20 14:07:45 -07005477 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5478 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005479 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005480 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005481 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005482 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005483 }
5484
Stuart Scotte3e314d2015-04-20 14:07:45 -07005485 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005486 // Remove always-on package
5487 synchronized (mVpns) {
5488 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5489 if (alwaysOnPackage != null) {
5490 setAlwaysOnVpnPackage(userId, null, false);
5491 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5492 }
5493 }
5494
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005495 // Turn Always-on VPN off
5496 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5497 final long ident = Binder.clearCallingIdentity();
5498 try {
5499 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5500 mLockdownEnabled = false;
5501 setLockdownTracker(null);
5502 } finally {
5503 Binder.restoreCallingIdentity(ident);
5504 }
5505 }
5506
Stuart Scotte3e314d2015-04-20 14:07:45 -07005507 // Turn VPN off
5508 VpnConfig vpnConfig = getVpnConfig(userId);
5509 if (vpnConfig != null) {
5510 if (vpnConfig.legacy) {
5511 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5512 } else {
5513 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5514 // in the future without user intervention.
5515 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005516
Victor Changb04a5ea2016-05-30 20:36:30 +01005517 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005518 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005519 }
5520 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005521
5522 Settings.Global.putString(mContext.getContentResolver(),
5523 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005524 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005525
5526 @VisibleForTesting
5527 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5528 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5529 return new NetworkMonitor(context, handler, nai, defaultRequest);
5530 }
Erik Kline48f12f22016-04-14 17:30:59 +09005531
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005532 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005533 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5534 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005535 }
5536
5537 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005538 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5539 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5540 }
5541
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005542 @VisibleForTesting
5543 public boolean hasService(String name) {
5544 return ServiceManager.checkService(name) != null;
5545 }
5546
Hugo Benichi64901e52017-10-19 14:42:40 +09005547 @VisibleForTesting
5548 protected IpConnectivityMetrics.Logger metricsLogger() {
5549 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5550 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005551 }
5552
5553 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005554 int[] transports = nai.networkCapabilities.getTransportTypes();
5555 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005556 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005557
5558 private static boolean toBool(int encodedBoolean) {
5559 return encodedBoolean != 0; // Only 0 means false.
5560 }
5561
5562 private static int encodeBool(boolean b) {
5563 return b ? 1 : 0;
5564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565}