blob: 4546bfbfbce2b0482cf97997f1ed7d85cac019d4 [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;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Hugo Benichia0385682017-03-22 17:07:57 +090032import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080035import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090036import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
41import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070043import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070044import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090046import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070048import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070049import android.net.INetworkPolicyListener;
50import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070051import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080052import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070053import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010054import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070055import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070056import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070057import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070058import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070060import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070061import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070062import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070064import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090072import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090073import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090074import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090075import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080077import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070078import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040079import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070081import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070082import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070083import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Looper;
85import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070086import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070087import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090088import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070091import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080092import android.os.ResultReceiver;
Hugo Benichicb883232017-05-11 13:16:17 +090093import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090094import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070095import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040096import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700100import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700101import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700102import android.util.LocalLog;
103import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600104import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800105import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700106import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500107import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700108import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700109import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Wink Savilleab9321d2013-06-29 21:10:57 -0700111import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400112import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400113import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700114import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700115import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700116import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700117import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800118import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700119import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700120import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600121import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700122import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900123import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900124import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700125import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700126import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400127import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900128import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100129import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700130import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900131import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700132import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600133import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400134import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900135import com.android.server.connectivity.NetworkNotificationManager;
136import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400137import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700138import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800139import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700140import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100141import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700142import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700143import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900144import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600145
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700146import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700147
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700148import org.xmlpull.v1.XmlPullParser;
149import org.xmlpull.v1.XmlPullParserException;
150
151import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700153import java.io.FileNotFoundException;
154import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700155import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700157import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700158import java.net.InetAddress;
159import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700160import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700161import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700162import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700163import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700164import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700165import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700166import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700167import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700168import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600169import java.util.SortedSet;
170import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172/**
173 * @hide
174 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800175public class ConnectivityService extends IConnectivityManager.Stub
176 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900177 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Erik Kline7747fd42017-05-12 16:52:48 +0900179 public static final String DIAG_ARG = "--diag";
180 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900181 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900182
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900183 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700184 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Jake Hamby786e71a2014-02-06 14:43:50 -0800186 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900187 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188
Jeff Sharkey899223b2012-08-04 15:24:58 -0700189 // TODO: create better separation between radio types and network types
190
Robert Greenwalt42acef32009-08-12 16:08:25 -0700191 // how long to wait before switching back to a radio's default network
192 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
193 // system property that can override the above value
194 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
195 "android.telephony.apn-restore";
196
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900197 // How long to wait before putting up a "This network doesn't have an Internet connection,
198 // connect anyway?" dialog after the user selects a network that doesn't validate.
199 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900201 // Default to 30s linger time-out. Modifiable only for testing.
202 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
203 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
204 @VisibleForTesting
205 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
206
Jeremy Joslin79294842014-12-03 17:15:28 -0800207 // How long to delay to removal of a pending intent based request.
208 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
209 private final int mReleasePendingIntentDelayMs;
210
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900211 private MockableSystemProperties mSystemProperties;
212
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800213 private Tethering mTethering;
214
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700215 private final PermissionMonitor mPermissionMonitor;
216
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700217 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700218
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700219 @GuardedBy("mVpns")
220 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700221
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700222 private boolean mLockdownEnabled;
223 private LockdownVpnTracker mLockdownTracker;
224
Erik Klineda4bfa82015-04-30 12:58:40 +0900225 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700227 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700228 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800230 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700233 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700235 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800236 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700237 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900238 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700239
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700240 private String mCurrentTcpBufferSizes;
241
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 private static final int ENABLED = 1;
243 private static final int DISABLED = 0;
244
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900245 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900246 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
247 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900248
Paul Jensenb10e37f2014-11-25 12:33:08 -0500249 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400250 // Tear down networks that have no chance (e.g. even if validated) of becoming
251 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500252 // all networks have been rematched against all NetworkRequests.
253 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400254 // Don't reap networks. This should be passed when some networks have not yet been
255 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 DONT_REAP
257 };
258
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900259 private enum UnneededFor {
260 LINGER, // Determine whether this network is unneeded and should be lingered.
261 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
262 }
263
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700264 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700265 * used internally to change our mobile data enabled flag
266 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700267 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700268
269 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700270 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700271 * from one net to another. Clear happens when we get a new
272 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
273 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700274 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700275 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700276
Robert Greenwalt434203a2010-10-11 16:00:27 -0700277 /**
278 * used internally to reload global proxy settings
279 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700280 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700281
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700282 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400283 * PAC manager has received new port.
284 */
285 private static final int EVENT_PROXY_HAS_CHANGED = 16;
286
Robert Greenwalte049c232014-04-11 15:53:27 -0700287 /**
288 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700289 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700290 */
291 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
292
Robert Greenwalt7b816022014-04-18 15:25:25 -0700293 /**
294 * used internally when registering NetworkAgents
295 * obj = Messenger
296 */
297 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
298
Robert Greenwalt9258c642014-03-26 16:47:06 -0700299 /**
300 * used to add a network request
301 * includes a NetworkRequestInfo
302 */
303 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
304
305 /**
306 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900307 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 * cancel it.
309 * includes a NetworkRequestInfo
310 */
311 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
312
313 /**
314 * used to add a network listener - no request
315 * includes a NetworkRequestInfo
316 */
317 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
318
319 /**
320 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400321 * arg1 = UID of caller
322 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700323 */
324 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
325
Robert Greenwalta67be032014-05-16 15:49:14 -0700326 /**
327 * used internally when registering NetworkFactories
328 * obj = Messenger
329 */
330 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
331
Robert Greenwalt27711812014-06-25 16:45:57 -0700332 /**
333 * used internally to expire a wakelock when transitioning
334 * from one net to another. Expire happens when we fail to find
335 * a new network (typically after 1 minute) -
336 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
337 * a replacement network.
338 */
339 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
340
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700341 /**
342 * Used internally to indicate the system is ready.
343 */
344 private static final int EVENT_SYSTEM_READY = 25;
345
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800346 /**
347 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400348 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800349 */
350 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
351
352 /**
353 * used to remove a pending intent and its associated network request.
354 * arg1 = UID of caller
355 * obj = PendingIntent
356 */
357 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
358
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900359 /**
360 * used to specify whether a network should be used even if unvalidated.
361 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
362 * arg2 = whether to remember this choice in the future (1 or 0)
363 * obj = network
364 */
365 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
366
367 /**
368 * used to ask the user to confirm a connection to an unvalidated network.
369 * obj = network
370 */
371 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700372
Erik Klineda4bfa82015-04-30 12:58:40 +0900373 /**
374 * used internally to (re)configure mobile data always-on settings.
375 */
376 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
377
Paul Jensen694f2b82015-06-17 14:15:39 -0400378 /**
379 * used to add a network listener with a pending intent
380 * obj = NetworkRequestInfo
381 */
382 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
383
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900384 /**
385 * used to specify whether a network should not be penalized when it becomes unvalidated.
386 */
387 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
388
389 /**
390 * used to trigger revalidation of a network.
391 */
392 private static final int EVENT_REVALIDATE_NETWORK = 36;
393
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900394 private static String eventName(int what) {
395 return sMagicDecoderRing.get(what, Integer.toString(what));
396 }
397
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900398 /** Handler thread used for both of the handlers below. */
399 @VisibleForTesting
400 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700401 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700402 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700403 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700404 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700405
Mike Lockwood0f79b542009-08-14 14:18:49 -0400406 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800407 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400408
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700409 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700410 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800411 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412
Robert Greenwalt434203a2010-10-11 16:00:27 -0700413 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400414 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700415 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700416 private boolean mDefaultProxyDisabled = false;
417
Robert Greenwalt434203a2010-10-11 16:00:27 -0700418 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400419 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420
Jason Monk602b2322013-07-03 17:04:33 -0400421 private PacManager mPacManager = null;
422
Erik Klineda4bfa82015-04-30 12:58:40 +0900423 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700424
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400425 private UserManager mUserManager;
426
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700427 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700428 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700429
Robert Greenwalt50393202011-06-21 17:26:14 -0700430 // the set of network types that can only be enabled by system/sig apps
431 List mProtectedNetworks;
432
John Spurlockbf991a82013-06-24 14:20:23 -0400433 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700434
Wink Savilleab9321d2013-06-29 21:10:57 -0700435 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400436
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900437 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900438 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900439 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900440
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700441 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
442 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700443 private final static int MAX_NET_ID = 65535;
444 private int mNextNetId = MIN_NET_ID;
445
Robert Greenwalt34524f02014-05-18 16:22:10 -0700446 // sequence number of NetworkRequests
447 private int mNextNetworkRequestId = 1;
448
Erik Kline7523eb32015-07-09 18:24:03 +0900449 // NetworkRequest activity String log entries.
450 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
451 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
452
Hugo Benichic2ae2872016-07-11 11:05:12 +0900453 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900454 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900455 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
456
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900457 private static final int MAX_WAKELOCK_LOGS = 20;
458 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900459 private int mTotalWakelockAcquisitions = 0;
460 private int mTotalWakelockReleases = 0;
461 private long mTotalWakelockDurationMs = 0;
462 private long mMaxWakelockDurationMs = 0;
463 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900464
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700465 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
466 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400467 private static class ValidationLog {
468 final Network mNetwork;
469 final String mNetworkExtraInfo;
470 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471
Paul Jensen0808eb82016-06-03 13:51:21 -0400472 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
473 mNetwork = network;
474 mNetworkExtraInfo = networkExtraInfo;
475 mLog = log;
476 }
477 }
478 private final ArrayDeque<ValidationLog> mValidationLogs =
479 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
480
481 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900482 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
484 mValidationLogs.removeLast();
485 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487 }
488 }
489
Hugo Benichif9fdf872016-07-28 17:53:06 +0900490 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900491
Erik Kline065ab6e2016-10-02 18:02:14 +0900492 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900493 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900494
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700495 /**
496 * Implements support for the legacy "one network per network type" model.
497 *
498 * We used to have a static array of NetworkStateTrackers, one for each
499 * network type, but that doesn't work any more now that we can have,
500 * for example, more that one wifi network. This class stores all the
501 * NetworkAgentInfo objects that support a given type, but the legacy
502 * API will only see the first one.
503 *
504 * It serves two main purposes:
505 *
506 * 1. Provide information about "the network for a given type" (since this
507 * API only supports one).
508 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
509 * the first network for a given type changes, or if the default network
510 * changes.
511 */
512 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900514 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 /**
518 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
519 * Each list holds references to all NetworkAgentInfos that are used to
520 * satisfy requests for that network type.
521 *
522 * This array is built out at startup such that an unsupported network
523 * doesn't get an ArrayList instance, making this a tristate:
524 * unsupported, supported but not active and active.
525 *
526 * The actual lists are populated when we scan the network types that
527 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900528 *
529 * Threading model:
530 * - addSupportedType() is only called in the constructor
531 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
532 * They are therefore not thread-safe with respect to each other.
533 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
534 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
535 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538
539 public LegacyTypeTracker() {
540 mTypeLists = (ArrayList<NetworkAgentInfo>[])
541 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
542 }
543
544 public void addSupportedType(int type) {
545 if (mTypeLists[type] != null) {
546 throw new IllegalStateException(
547 "legacy list for type " + type + "already initialized");
548 }
549 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
550 }
551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 public boolean isTypeSupported(int type) {
553 return isNetworkTypeValid(type) && mTypeLists[type] != null;
554 }
555
556 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900557 synchronized (mTypeLists) {
558 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
559 return mTypeLists[type].get(0);
560 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900566 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 }
572 }
573
574 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public void add(int type, NetworkAgentInfo nai) {
576 if (!isTypeSupported(type)) {
577 return; // Invalid network type.
578 }
579 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
580
581 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
582 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 return;
584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 synchronized (mTypeLists) {
586 list.add(nai);
587 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900588
589 // 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 +0900590 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900591 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
593 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
596
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900598 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
600 if (list == null || list.isEmpty()) {
601 return;
602 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 synchronized (mTypeLists) {
606 if (!list.remove(nai)) {
607 return;
608 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 final DetailedState state = DetailedState.DISCONNECTED;
612
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 maybeLogBroadcast(nai, state, type, wasDefault);
615 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 }
617
618 if (!list.isEmpty() && wasFirstNetwork) {
619 if (DBG) log("Other network available for type " + type +
620 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
623 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625 }
626
627 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
629 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 }
633 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700634
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 // send out another legacy broadcast - currently only used for suspend/unsuspend
636 // toggle
637 public void update(NetworkAgentInfo nai) {
638 final boolean isDefault = isDefaultNetwork(nai);
639 final DetailedState state = nai.networkInfo.getDetailedState();
640 for (int type = 0; type < mTypeLists.length; type++) {
641 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700642 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900643 final boolean isFirst = contains && (nai == list.get(0));
644 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(nai, state, type, isDefault);
646 sendLegacyNetworkBroadcast(nai, state, type);
647 }
648 }
649 }
650
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 private String naiToString(NetworkAgentInfo nai) {
652 String name = (nai != null) ? nai.name() : "null";
653 String state = (nai.networkInfo != null) ?
654 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
655 "???/???";
656 return name + " " + state;
657 }
658
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700659 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900660 pw.println("mLegacyTypeTracker:");
661 pw.increaseIndent();
662 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 pw.println();
667 pw.println("Current state:");
668 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900669 synchronized (mTypeLists) {
670 for (int type = 0; type < mTypeLists.length; type++) {
671 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
672 for (NetworkAgentInfo nai : mTypeLists[type]) {
673 pw.println(type + " " + naiToString(nai));
674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 }
676 }
677 pw.decreaseIndent();
678 pw.decreaseIndent();
679 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700680 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700681 }
682 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
683
Jeff Sharkey899223b2012-08-04 15:24:58 -0700684 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700685 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900686 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
687 }
688
689 @VisibleForTesting
690 protected ConnectivityService(Context context, INetworkManagementService netManager,
691 INetworkStatsService statsService, INetworkPolicyManager policyManager,
692 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800693 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800694
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900695 mSystemProperties = getSystemProperties();
696
Hugo Benichif9fdf872016-07-28 17:53:06 +0900697 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900698 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900699 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900700 mNetworkRequests.put(mDefaultRequest, defaultNRI);
701 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900702
703 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900704 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700705
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900706 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900707 mHandlerThread.start();
708 mHandler = new InternalHandler(mHandlerThread.getLooper());
709 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700710
Jeremy Joslin79294842014-12-03 17:15:28 -0800711 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
712 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
713
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900714 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900715
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700716 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700717 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800718 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700719 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900720 mPolicyManagerInternal = checkNotNull(
721 LocalServices.getService(NetworkPolicyManagerInternal.class),
722 "missing NetworkPolicyManagerInternal");
723
Jeff Sharkey82f85212012-08-24 11:17:25 -0700724 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700725 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700726
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900728 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 } catch (RemoteException e) {
730 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700731 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 }
733
734 final PowerManager powerManager = (PowerManager) context.getSystemService(
735 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700736 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
737 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
738 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800739 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700740
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700741 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700742
Wink Saville51f456f2013-04-23 14:26:51 -0700743 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900744 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700745 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746 String[] naStrings = context.getResources().getStringArray(
747 com.android.internal.R.array.networkAttributes);
748 for (String naString : naStrings) {
749 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700751 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700752 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800753 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700754 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700756 }
Wink Saville51f456f2013-04-23 14:26:51 -0700757 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
758 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
759 n.type);
760 continue;
761 }
Wink Saville975c8482011-04-07 14:23:45 -0700762 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800763 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700764 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 continue;
766 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700767 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700768
Wink Saville975c8482011-04-07 14:23:45 -0700769 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700770 mNetworksDefined++;
771 } catch(Exception e) {
772 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700773 }
774 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700775
776 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
777 if (mNetConfigs[TYPE_VPN] == null) {
778 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
779 // don't need to add TYPE_VPN to mNetConfigs.
780 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
781 mNetworksDefined++; // used only in the log() statement below.
782 }
783
Wink Saville5e56bc52013-07-29 15:00:57 -0700784 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700785
Robert Greenwalt50393202011-06-21 17:26:14 -0700786 mProtectedNetworks = new ArrayList<Integer>();
787 int[] protectedNetworks = context.getResources().getIntArray(
788 com.android.internal.R.array.config_protectedNetworks);
789 for (int p : protectedNetworks) {
790 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
791 mProtectedNetworks.add(p);
792 } else {
793 if (DBG) loge("Ignoring protectedNetwork " + p);
794 }
795 }
796
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900797 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
798 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700799
Erik Kline47222fc2017-04-30 19:36:15 +0900800 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800801
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700802 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
803
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700804 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700805 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100806 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700807 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700808 intentFilter.addAction(Intent.ACTION_USER_ADDED);
809 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000810 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700811 mContext.registerReceiverAsUser(
812 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000813 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
814 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900815
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700816 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700817 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700818 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700819 } catch (RemoteException e) {
820 loge("Error registering observer :" + e);
821 }
822
Erik Klineda4bfa82015-04-30 12:58:40 +0900823 mSettingsObserver = new SettingsObserver(mContext, mHandler);
824 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800825
John Spurlockbf991a82013-06-24 14:20:23 -0400826 mDataConnectionStats = new DataConnectionStats(mContext);
827 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400828
Jason Monkdecd2952013-10-10 14:02:51 -0400829 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700830
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400831 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900832
833 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900834 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
835 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900836
837 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
838 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
839 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
840 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
841 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
842 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
843 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900844
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900845 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900846 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900847 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700849
Erik Kline47222fc2017-04-30 19:36:15 +0900850 private Tethering makeTethering() {
851 // TODO: Move other elements into @Overridden getters.
852 final TetheringDependencies deps = new TetheringDependencies();
853 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
854 IoThread.get().getLooper(), new MockableSystemProperties(),
855 deps);
856 }
857
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900858 private NetworkRequest createInternetRequestForTransport(
859 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900860 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900861 netCap.addCapability(NET_CAPABILITY_INTERNET);
862 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900863 if (transportType > -1) {
864 netCap.addTransportType(transportType);
865 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900866 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900867 }
868
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900869 // Used only for testing.
870 // TODO: Delete this and either:
871 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
872 // changing ContentResolver to make registerContentObserver non-final).
873 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
874 // by subclassing SettingsObserver.
875 @VisibleForTesting
876 void updateMobileDataAlwaysOn() {
877 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
878 }
879
Erik Klineda4bfa82015-04-30 12:58:40 +0900880 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900881 final boolean enable = toBool(Settings.Global.getInt(
882 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900883 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
884 if (enable == isEnabled) {
885 return; // Nothing to do.
886 }
887
888 if (enable) {
889 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900890 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900891 } else {
892 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
893 }
894 }
895
896 private void registerSettingsCallbacks() {
897 // Watch for global HTTP proxy changes.
898 mSettingsObserver.observe(
899 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
900 EVENT_APPLY_GLOBAL_HTTP_PROXY);
901
902 // Watch for whether or not to keep mobile data always on.
903 mSettingsObserver.observe(
904 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
905 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
906 }
907
Robert Greenwalt34524f02014-05-18 16:22:10 -0700908 private synchronized int nextNetworkRequestId() {
909 return mNextNetworkRequestId++;
910 }
911
Paul Jensen67b0b072015-06-10 11:22:17 -0400912 @VisibleForTesting
913 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400914 synchronized (mNetworkForNetId) {
915 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
916 int netId = mNextNetId;
917 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
918 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500919 if (!mNetIdInUse.get(netId)) {
920 mNetIdInUse.put(netId, true);
921 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400922 }
923 }
924 }
925 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700926 }
927
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600928 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600930 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
931 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600933 state = nai.getNetworkState();
934 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600936 final NetworkInfo info = new NetworkInfo(networkType, 0,
937 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
939 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
941 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600943 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 return state;
945 } else {
946 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400948 }
949
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
951 if (network == null) {
952 return null;
953 }
954 synchronized (mNetworkForNetId) {
955 return mNetworkForNetId.get(network.netId);
956 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600957 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900959 private Network[] getVpnUnderlyingNetworks(int uid) {
960 if (!mLockdownEnabled) {
961 int user = UserHandle.getUserId(uid);
962 synchronized (mVpns) {
963 Vpn vpn = mVpns.get(user);
964 if (vpn != null && vpn.appliesToUid(uid)) {
965 return vpn.getUnderlyingNetworks();
966 }
967 }
968 }
969 return null;
970 }
971
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400973 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800974
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900975 final Network[] networks = getVpnUnderlyingNetworks(uid);
976 if (networks != null) {
977 // getUnderlyingNetworks() returns:
978 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
979 // empty array => the VPN explicitly said "no default network".
980 // non-empty array => the VPN specified one or more default networks; we use the
981 // first one.
982 if (networks.length > 0) {
983 nai = getNetworkAgentInfoForNetwork(networks[0]);
984 } else {
985 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800986 }
987 }
988
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 return nai.getNetworkState();
991 } else {
992 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400994 }
995
996 /**
997 * Check if UID should be blocked from using the network with the given LinkProperties.
998 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600999 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1000 boolean ignoreBlocked) {
1001 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001002 if (ignoreBlocked) {
1003 return false;
1004 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001005 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001006 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1007 if (isSystem(uid)) {
1008 return false;
1009 }
Robin Lee17e61832016-05-09 13:46:28 +01001010 synchronized (mVpns) {
1011 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1012 if (vpn != null && vpn.isBlockingUid(uid)) {
1013 return true;
1014 }
1015 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001016 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001017 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001018 }
1019
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001020 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001021 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1022 return;
1023 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001024 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001025 synchronized (mBlockedAppUids) {
1026 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001027 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001028 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001029 blocked = false;
1030 } else {
1031 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001032 }
1033 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001034 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1035 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1036 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001037 }
1038
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001040 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1041 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001042 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001044 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001045 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1046
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001047 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001049 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 if (mLockdownTracker != null) {
1051 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001052 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 }
1054
1055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 * Return NetworkInfo for the active (i.e., connected) network interface.
1057 * It is assumed that at most one network is active at a time. If more
1058 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001059 * @return the info for the active network, or {@code null} if none is
1060 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001062 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 enforceAccessPermission();
1065 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001067 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001068 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1069 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
1071
Paul Jensen31a94f42015-02-13 14:18:39 -05001072 @Override
1073 public Network getActiveNetwork() {
1074 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001075 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001076 }
1077
1078 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001080 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001082 }
1083
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001085 final int user = UserHandle.getUserId(uid);
1086 int vpnNetId = NETID_UNSET;
1087 synchronized (mVpns) {
1088 final Vpn vpn = mVpns.get(user);
1089 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1090 }
1091 NetworkAgentInfo nai;
1092 if (vpnNetId != NETID_UNSET) {
1093 synchronized (mNetworkForNetId) {
1094 nai = mNetworkForNetId.get(vpnNetId);
1095 }
1096 if (nai != null) return nai.network;
1097 }
1098 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001099 if (nai != null
1100 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1101 nai = null;
1102 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001103 return nai != null ? nai.network : null;
1104 }
1105
Lorenzo Colitti18660282016-07-04 12:55:44 +09001106 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001107 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1108 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001109 final int uid = Binder.getCallingUid();
1110 NetworkState state = getUnfilteredActiveNetworkState(uid);
1111 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001112 }
1113
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001114 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001116 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001117 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001118 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001119 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001120 }
1121
1122 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 public NetworkInfo getNetworkInfo(int networkType) {
1124 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001125 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001126 if (getVpnUnderlyingNetworks(uid) != null) {
1127 // A VPN is active, so we may need to return one of its underlying networks. This
1128 // information is not available in LegacyTypeTracker, so we have to get it from
1129 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001130 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001131 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001134 }
1135 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001146 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001147 return state.networkInfo;
1148 } else {
1149 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 }
1152
1153 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 public NetworkInfo[] getAllNetworkInfo() {
1155 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001156 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001157 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1158 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 NetworkInfo info = getNetworkInfo(networkType);
1160 if (info != null) {
1161 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001164 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001167 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001168 public Network getNetworkForType(int networkType) {
1169 enforceAccessPermission();
1170 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1172 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001174 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001176 }
1177
1178 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 public Network[] getAllNetworks() {
1180 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001181 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001182 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001183 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001184 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001185 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001186 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 }
1189
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001190 @Override
1191 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1192 // The basic principle is: if an app's traffic could possibly go over a
1193 // network, without the app doing anything multinetwork-specific,
1194 // (hence, by "default"), then include that network's capabilities in
1195 // the array.
1196 //
1197 // In the normal case, app traffic only goes over the system's default
1198 // network connection, so that's the only network returned.
1199 //
1200 // With a VPN in force, some app traffic may go into the VPN, and thus
1201 // over whatever underlying networks the VPN specifies, while other app
1202 // traffic may go over the system default network (e.g.: a split-tunnel
1203 // VPN, or an app disallowed by the VPN), so the set of networks
1204 // returned includes the VPN's underlying networks and the system
1205 // default.
1206 enforceAccessPermission();
1207
1208 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1209
1210 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001211 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001212 if (nc != null) {
1213 result.put(nai.network, nc);
1214 }
1215
1216 if (!mLockdownEnabled) {
1217 synchronized (mVpns) {
1218 Vpn vpn = mVpns.get(userId);
1219 if (vpn != null) {
1220 Network[] networks = vpn.getUnderlyingNetworks();
1221 if (networks != null) {
1222 for (Network network : networks) {
1223 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001224 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001225 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001226 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001227 }
1228 }
1229 }
1230 }
1231 }
1232 }
1233
1234 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1235 out = result.values().toArray(out);
1236 return out;
1237 }
1238
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001239 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001240 public boolean isNetworkSupported(int networkType) {
1241 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001242 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001243 }
1244
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001245 /**
1246 * Return LinkProperties for the active (i.e., connected) default
1247 * network interface. It is assumed that at most one default network
1248 * is active at a time. If more than one is active, it is indeterminate
1249 * which will be returned.
1250 * @return the ip properties for the active network, or {@code null} if
1251 * none is active
1252 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001253 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001254 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 enforceAccessPermission();
1256 final int uid = Binder.getCallingUid();
1257 NetworkState state = getUnfilteredActiveNetworkState(uid);
1258 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001259 }
1260
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001262 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001263 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1265 if (nai != null) {
1266 synchronized (nai) {
1267 return new LinkProperties(nai.linkProperties);
1268 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001269 }
1270 return null;
1271 }
1272
Robert Greenwalt12e67352014-05-13 21:41:06 -07001273 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001274 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001275 public LinkProperties getLinkProperties(Network network) {
1276 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001277 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1278 }
1279
1280 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1281 if (nai == null) {
1282 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001283 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001284 synchronized (nai) {
1285 return new LinkProperties(nai.linkProperties);
1286 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001287 }
1288
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001289 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001290 if (nai != null) {
1291 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001292 if (nai.networkCapabilities != null) {
1293 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001294 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001295 }
1296 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001297 return null;
1298 }
1299
1300 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001301 public NetworkCapabilities getNetworkCapabilities(Network network) {
1302 enforceAccessPermission();
1303 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1304 }
1305
1306 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001307 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001308 // Require internal since we're handing out IMSI details
1309 enforceConnectivityInternalPermission();
1310
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001311 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001312 for (Network network : getAllNetworks()) {
1313 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1314 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001315 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001316 }
1317 }
1318 return result.toArray(new NetworkState[result.size()]);
1319 }
1320
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001321 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001322 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001323 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001324 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1325 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1326 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001327 }
1328
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001329 @Override
1330 public boolean isActiveNetworkMetered() {
1331 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001332
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001333 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1334 if (caps != null) {
1335 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1336 } else {
1337 // Always return the most conservative value
1338 return true;
1339 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001340 }
1341
Jeff Sharkey216c1812012-08-05 14:29:23 -07001342 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1343 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001344 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001345 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001346 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001347 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001348 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001349
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001350 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 * Ensure that a network route exists to deliver traffic to the specified
1352 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001353 * @param networkType the type of the network over which traffic to the
1354 * specified host is to be routed
1355 * @param hostAddress the IP address of the host to which the route is
1356 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 * @return {@code true} on success, {@code false} on failure
1358 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001359 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001360 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001362 if (mProtectedNetworks.contains(networkType)) {
1363 enforceConnectivityInternalPermission();
1364 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001365
Chad Brubakerc0234532014-02-14 13:24:29 -08001366 InetAddress addr;
1367 try {
1368 addr = InetAddress.getByAddress(hostAddress);
1369 } catch (UnknownHostException e) {
1370 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1371 return false;
1372 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001375 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 return false;
1377 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001378
1379 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1380 if (nai == null) {
1381 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1382 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1383 } else {
1384 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1385 }
1386 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001387 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001388
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001389 DetailedState netState;
1390 synchronized (nai) {
1391 netState = nai.networkInfo.getDetailedState();
1392 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001393
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001394 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001395 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001396 log("requestRouteToHostAddress on down network "
1397 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001398 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001399 }
1400 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001402
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001403 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001404 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001405 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001406 LinkProperties lp;
1407 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001408 synchronized (nai) {
1409 lp = nai.linkProperties;
1410 netId = nai.network.netId;
1411 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001412 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001413 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1414 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001415 } finally {
1416 Binder.restoreCallingIdentity(token);
1417 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001418 }
1419
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001420 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001421 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001422 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001423 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001424 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001425 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001426 if (bestRoute.getGateway().equals(addr)) {
1427 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001428 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001429 } else {
1430 // if we will connect to this through another route, add a direct route
1431 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001432 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001433 }
1434 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001435 if (DBG) log("Adding legacy route " + bestRoute +
1436 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437 try {
1438 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1439 } catch (Exception e) {
1440 // never crash - catch them all
1441 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001442 return false;
1443 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001444 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001447 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001448 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001449 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001450 // TODO: notify UID when it has requested targeted updates
1451 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001452 @Override
1453 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001454 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001455 @Override
1456 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001457 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001458 if (restrictBackground) {
1459 log("onRestrictBackgroundChanged(true): disabling tethering");
1460 mTethering.untetherAll();
1461 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001462 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001463 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001464 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001465 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001466 };
1467
Robin Lee3b3dd942015-05-12 18:14:58 +01001468 /**
1469 * Require that the caller is either in the same user or has appropriate permission to interact
1470 * across users.
1471 *
1472 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1473 */
1474 private void enforceCrossUserPermission(int userId) {
1475 if (userId == UserHandle.getCallingUserId()) {
1476 // Not a cross-user call.
1477 return;
1478 }
1479 mContext.enforceCallingOrSelfPermission(
1480 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1481 "ConnectivityService");
1482 }
1483
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001484 private void enforceInternetPermission() {
1485 mContext.enforceCallingOrSelfPermission(
1486 android.Manifest.permission.INTERNET,
1487 "ConnectivityService");
1488 }
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001491 mContext.enforceCallingOrSelfPermission(
1492 android.Manifest.permission.ACCESS_NETWORK_STATE,
1493 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
1496 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001497 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499
Charles He36738632017-05-15 17:07:18 +01001500 private void enforceSettingsPermission() {
1501 mContext.enforceCallingOrSelfPermission(
1502 android.Manifest.permission.NETWORK_SETTINGS,
1503 "ConnectivityService");
1504 }
1505
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001506 private void enforceTetherAccessPermission() {
1507 mContext.enforceCallingOrSelfPermission(
1508 android.Manifest.permission.ACCESS_NETWORK_STATE,
1509 "ConnectivityService");
1510 }
1511
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001512 private void enforceConnectivityInternalPermission() {
1513 mContext.enforceCallingOrSelfPermission(
1514 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1515 "ConnectivityService");
1516 }
1517
Hugo Benichi514da602016-07-19 15:59:27 +09001518 private void enforceConnectivityRestrictedNetworksPermission() {
1519 try {
1520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1522 "ConnectivityService");
1523 return;
1524 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1525 enforceConnectivityInternalPermission();
1526 }
1527
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001528 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001529 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001530 }
1531
Lorenzo Colitti18660282016-07-04 12:55:44 +09001532 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001533 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001534 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001535 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001536 }
1537
1538 private void sendInetConditionBroadcast(NetworkInfo info) {
1539 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1540 }
1541
Wink Saville628b0852011-08-04 15:01:58 -07001542 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001543 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001544 info = new NetworkInfo(info);
1545 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001546 }
1547
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001548 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001549 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001550 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 if (info.isFailover()) {
1552 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1553 info.setFailover(false);
1554 }
1555 if (info.getReason() != null) {
1556 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1557 }
1558 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001559 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1560 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001562 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001563 return intent;
1564 }
1565
1566 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1567 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1568 }
1569
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001570 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001571 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1572 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1573 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001574 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001575 final long ident = Binder.clearCallingIdentity();
1576 try {
1577 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1578 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1579 } finally {
1580 Binder.restoreCallingIdentity(ident);
1581 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001582 }
1583
Mike Lockwood0f79b542009-08-14 14:18:49 -04001584 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001585 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001586 if (!mSystemReady) {
1587 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001588 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001589 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001590 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001591 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001592 }
1593
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001594 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001595 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001596 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001597 final NetworkInfo ni = intent.getParcelableExtra(
1598 ConnectivityManager.EXTRA_NETWORK_INFO);
1599 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1600 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1601 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001602 } else {
1603 BroadcastOptions opts = BroadcastOptions.makeBasic();
1604 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1605 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001606 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001607 final IBatteryStats bs = BatteryStatsService.getService();
1608 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001609 bs.noteConnectivityChanged(intent.getIntExtra(
1610 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1611 ni != null ? ni.getState().toString() : "?");
1612 } catch (RemoteException e) {
1613 }
1614 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001615 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001616 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001617 } finally {
1618 Binder.restoreCallingIdentity(ident);
1619 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001620 }
1621 }
1622
1623 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001624 loadGlobalProxy();
1625
Hugo Benichi20035e02017-04-26 14:53:28 +09001626 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001627 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001628 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001629 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001630 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001631 }
1632 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001633 // load the global proxy at startup
1634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001635
Robin Lee244ce8e2016-01-05 18:03:46 +00001636 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1637 // for user to unlock device too.
1638 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001639
Erik Klineda4bfa82015-04-30 12:58:40 +09001640 // Configure whether mobile data is always on.
1641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1642
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001643 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001644
1645 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001649 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001650 *
1651 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001652 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001653 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001654 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1655 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001656
1657 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001659
Robert Greenwalt7b816022014-04-18 15:25:25 -07001660 if (networkAgent.networkCapabilities.hasTransport(
1661 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001662 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1663 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001664 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001665 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 } else if (networkAgent.networkCapabilities.hasTransport(
1667 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001668 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1669 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001670 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001671 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001672 } else {
1673 // do not track any other networks
1674 timeout = 0;
1675 }
1676
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001678 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001679 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001680 } catch (Exception e) {
1681 // You shall not crash!
1682 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001683 }
1684 }
1685 }
1686
1687 /**
1688 * Remove data activity tracking when network disconnects.
1689 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001690 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1691 final String iface = networkAgent.linkProperties.getInterfaceName();
1692 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001693
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1695 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001696 try {
1697 // the call fails silently if no idletimer setup for this interface
1698 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001699 } catch (Exception e) {
1700 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001701 }
1702 }
1703 }
1704
1705 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001706 * Reads the network specific MTU size from reources.
1707 * and set it on it's iface.
1708 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001709 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1710 final String iface = newLp.getInterfaceName();
1711 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001712 if (oldLp == null && mtu == 0) {
1713 // Silently ignore unset MTU value.
1714 return;
1715 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001716 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1717 if (VDBG) log("identical MTU - not setting");
1718 return;
1719 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001720 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001721 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001722 return;
1723 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001724
w1997615afd812014-08-05 15:18:11 -07001725 // Cannot set MTU without interface name
1726 if (TextUtils.isEmpty(iface)) {
1727 loge("Setting MTU size with null iface.");
1728 return;
1729 }
1730
Robert Greenwalt7b816022014-04-18 15:25:25 -07001731 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001732 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 mNetd.setMtu(iface, mtu);
1734 } catch (Exception e) {
1735 Slog.e(TAG, "exception in setMtu()" + e);
1736 }
1737 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001738
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001739 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001740 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1741
1742 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001743 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001744 protected MockableSystemProperties getSystemProperties() {
1745 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001746 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001747
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001748 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1749 if (isDefaultNetwork(nai) == false) {
1750 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001751 }
1752
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001753 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1754 String[] values = null;
1755 if (tcpBufferSizes != null) {
1756 values = tcpBufferSizes.split(",");
1757 }
1758
1759 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001760 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001761 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1762 values = tcpBufferSizes.split(",");
1763 }
1764
1765 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1766
1767 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001768 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001769
1770 final String prefix = "/sys/kernel/ipv4/tcp_";
1771 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1772 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1773 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1774 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1775 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1776 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1777 mCurrentTcpBufferSizes = tcpBufferSizes;
1778 } catch (IOException e) {
1779 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001780 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001781
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001782 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001783 Settings.Global.TCP_DEFAULT_INIT_RWND,
1784 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001785 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1786 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001787 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001788 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001789 }
1790
Mattias Falk8b47b362011-08-23 14:15:13 +02001791 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001792 /*
1793 * Tell the VMs to toss their DNS caches
1794 */
1795 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1796 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001797 /*
1798 * Connectivity events can happen before boot has completed ...
1799 */
1800 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001801 final long ident = Binder.clearCallingIdentity();
1802 try {
1803 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1804 } finally {
1805 Binder.restoreCallingIdentity(ident);
1806 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001807 }
1808
Robert Greenwalt562cc542014-05-15 18:07:26 -07001809 @Override
1810 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001811 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001812 NETWORK_RESTORE_DELAY_PROP_NAME);
1813 if(restoreDefaultNetworkDelayStr != null &&
1814 restoreDefaultNetworkDelayStr.length() != 0) {
1815 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001816 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001817 } catch (NumberFormatException e) {
1818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001820 // if the system property isn't set, use the value for the apn type
1821 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1822
1823 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1824 (mNetConfigs[networkType] != null)) {
1825 ret = mNetConfigs[networkType].restoreTime;
1826 }
1827 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001830 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001831 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001832 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001833 }
1834 return false;
1835 }
1836
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001837 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1838 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1839 final long DIAG_TIME_MS = 5000;
1840 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1841 // Start gathering diagnostic information.
1842 netDiags.add(new NetworkDiagnostics(
1843 nai.network,
1844 new LinkProperties(nai.linkProperties), // Must be a copy.
1845 DIAG_TIME_MS));
1846 }
1847
1848 for (NetworkDiagnostics netDiag : netDiags) {
1849 pw.println();
1850 netDiag.waitForMeasurements();
1851 netDiag.dump(pw);
1852 }
1853 }
1854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1857 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001858 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001859
Erik Kline7747fd42017-05-12 16:52:48 +09001860 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001861 dumpNetworkDiagnostics(pw);
1862 return;
Erik Klineee363c42017-05-29 09:11:03 +09001863 } else if (argsContain(args, TETHERING_ARG)) {
1864 mTethering.dump(fd, pw, args);
1865 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001866 }
Erik Kline379747a2015-06-05 17:47:34 +09001867
Lorenzo Colittie3805462015-06-03 11:18:24 +09001868 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001869 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001870 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001871 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001872 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001873 pw.println();
1874
Paul Jensen85cf78e2015-06-25 13:25:07 -04001875 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001876 pw.print("Active default network: ");
1877 if (defaultNai == null) {
1878 pw.println("none");
1879 } else {
1880 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001882 pw.println();
1883
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001884 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001885 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001886 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1887 pw.println(nai.toString());
1888 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001889 pw.println(String.format(
1890 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1891 nai.numForegroundNetworkRequests(),
1892 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1893 nai.numBackgroundNetworkRequests(),
1894 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001895 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001896 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1897 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001898 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001899 pw.decreaseIndent();
1900 pw.println("Lingered:");
1901 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001902 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001903 pw.decreaseIndent();
1904 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001905 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001906 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001907 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001908
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001909 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001910 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001911 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1912 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001913 }
1914 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001915 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001916
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001917 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001918
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001919 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001920 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001921
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001922 pw.println();
1923 mKeepaliveTracker.dump(pw);
1924
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001925 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001926 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001927
Erik Kline7747fd42017-05-12 16:52:48 +09001928 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001929 pw.println();
1930 synchronized (mValidationLogs) {
1931 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001932 for (ValidationLog p : mValidationLogs) {
1933 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001934 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001935 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001936 pw.decreaseIndent();
1937 }
1938 }
Erik Kline7523eb32015-07-09 18:24:03 +09001939
1940 pw.println();
1941 pw.println("mNetworkRequestInfoLogs (most recent first):");
1942 pw.increaseIndent();
1943 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1944 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001945
1946 pw.println();
1947 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1948 pw.increaseIndent();
1949 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1950 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001951
1952 pw.println();
1953 pw.println("NetTransition WakeLock activity (most recent first):");
1954 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09001955 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1956 pw.println("total releases: " + mTotalWakelockReleases);
1957 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1958 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1959 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1960 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1961 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1962 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001963 mWakelockLogs.reverseDump(fd, pw, args);
1964 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001968 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001969 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001970 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001971 if (officialNai != null && officialNai.equals(nai)) return true;
1972 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001973 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001974 " - " + nai);
1975 }
1976 return false;
1977 }
1978
Robert Greenwalt42acef32009-08-12 16:08:25 -07001979 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001980 private class NetworkStateTrackerHandler extends Handler {
1981 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001982 super(looper);
1983 }
1984
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001985 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001987 default:
1988 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001989 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001990 handleAsyncChannelHalfConnect(msg);
1991 break;
1992 }
1993 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1994 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1995 if (nai != null) nai.asyncChannel.disconnect();
1996 break;
1997 }
1998 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1999 handleAsyncChannelDisconnected(msg);
2000 break;
2001 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002002 }
2003 return true;
2004 }
2005
2006 private void maybeHandleNetworkAgentMessage(Message msg) {
2007 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2008 if (nai == null) {
2009 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002010 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002011 }
2012 return;
2013 }
2014
2015 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002016 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2018 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002019 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2020 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002021 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002022 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002023 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002024 break;
2025 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002026 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichi37119102017-08-31 14:32:54 +00002027 if (VDBG) {
2028 log("Update of LinkProperties for " + nai.name() +
2029 "; created=" + nai.created +
2030 "; everConnected=" + nai.everConnected);
2031 }
2032 LinkProperties oldLp = nai.linkProperties;
2033 synchronized (nai) {
2034 nai.linkProperties = (LinkProperties)msg.obj;
2035 }
2036 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 break;
2038 }
2039 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002040 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 updateNetworkInfo(nai, info);
2042 break;
2043 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002044 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002045 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002046 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002047 break;
2048 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002049 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002050 try {
2051 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002052 } catch (Exception e) {
2053 // Never crash!
2054 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002055 }
2056 break;
2057 }
2058 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002059 try {
2060 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002061 } catch (Exception e) {
2062 // Never crash!
2063 loge("Exception in removeVpnUidRanges: " + e);
2064 }
2065 break;
2066 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002067 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002068 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2069 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002070 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002071 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002072 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002073 break;
2074 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002075 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002076 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2077 break;
2078 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002079 }
2080 }
2081
2082 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2083 switch (msg.what) {
2084 default:
2085 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002086 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002087 final NetworkAgentInfo nai;
2088 synchronized (mNetworkForNetId) {
2089 nai = mNetworkForNetId.get(msg.arg2);
2090 }
2091 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002092 final boolean valid =
2093 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002094 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002095 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2096 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002097 if (valid != nai.lastValidated) {
2098 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002099 nai.lastValidated = valid;
2100 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002101 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002102 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2103 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002104 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002105 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002106 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002107 Bundle redirectUrlBundle = new Bundle();
2108 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002109 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002110 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002111 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002112 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002113 if (wasValidated && !nai.lastValidated) {
2114 handleNetworkUnvalidated(nai);
2115 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 break;
2118 }
Paul Jensen869868be2014-05-15 10:33:05 -04002119 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002120 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002121 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002122 final NetworkAgentInfo nai;
2123 synchronized (mNetworkForNetId) {
2124 nai = mNetworkForNetId.get(netId);
2125 }
Calvin Onbe96da12016-10-11 15:10:46 -07002126 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002127 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002128 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002129 nai.lastCaptivePortalDetected = visible;
2130 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002131 if (nai.lastCaptivePortalDetected &&
2132 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2133 if (DBG) log("Avoiding captive portal network: " + nai.name());
2134 nai.asyncChannel.sendMessage(
2135 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2136 teardownUnneededNetwork(nai);
2137 break;
2138 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002139 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002140 }
2141 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002142 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002143 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002144 if (nai == null) {
2145 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2146 break;
2147 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002148 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002149 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002150 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002151 }
Paul Jensen869868be2014-05-15 10:33:05 -04002152 }
Paul Jensen869868be2014-05-15 10:33:05 -04002153 break;
2154 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002155 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002156 return true;
2157 }
2158
Calvin Onbe96da12016-10-11 15:10:46 -07002159 private int getCaptivePortalMode() {
2160 return Settings.Global.getInt(mContext.getContentResolver(),
2161 Settings.Global.CAPTIVE_PORTAL_MODE,
2162 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2163 }
2164
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002165 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2166 switch (msg.what) {
2167 default:
2168 return false;
2169 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2170 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2171 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2172 handleLingerComplete(nai);
2173 }
2174 break;
2175 }
2176 }
2177 return true;
2178 }
2179
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002180 @Override
2181 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002182 if (!maybeHandleAsyncChannelMessage(msg) &&
2183 !maybeHandleNetworkMonitorMessage(msg) &&
2184 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 maybeHandleNetworkAgentMessage(msg);
2186 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002187 }
2188 }
2189
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002190 private void updateLingerState(NetworkAgentInfo nai, long now) {
2191 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2192 // 2. If the network was lingering and there are now requests, unlinger it.
2193 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2194 // one lingered request, start lingering.
2195 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002196 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002197 if (DBG) log("Unlingering " + nai.name());
2198 nai.unlinger();
2199 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002200 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002201 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002202 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002203 nai.linger();
2204 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2205 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2206 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002207 }
2208
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 private void handleAsyncChannelHalfConnect(Message msg) {
2210 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002211 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2213 if (VDBG) log("NetworkFactory connected");
2214 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002215 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002216 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002218 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002219 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 }
2221 } else {
2222 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002223 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002224 }
2225 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2226 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2227 if (VDBG) log("NetworkAgent connected");
2228 // A network agent has requested a connection. Establish the connection.
2229 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2230 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2231 } else {
2232 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002233 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002234 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002235 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002236 synchronized (mNetworkForNetId) {
2237 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002238 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002239 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002240 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002241 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002242 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002243 }
2244 }
2245 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002246
Robert Greenwalt7b816022014-04-18 15:25:25 -07002247 private void handleAsyncChannelDisconnected(Message msg) {
2248 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2249 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002250 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002251 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002252 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002253 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002254 // TODO - if we move the logic to the network agent (have them disconnect
2255 // because they lost all their requests or because their score isn't good)
2256 // then they would disconnect organically, report their new state and then
2257 // disconnect the channel.
2258 if (nai.networkInfo.isConnected()) {
2259 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2260 null, null);
2261 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002262 final boolean wasDefault = isDefaultNetwork(nai);
2263 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002264 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002265 // Log default network disconnection before required book-keeping.
2266 // Let rematchAllNetworksAndRequests() below record a new default network event
2267 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2268 // whose timestamps tell how long it takes to recover a default network.
2269 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002270 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002271 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002272 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2273 // by other networks that are already connected. Perhaps that can be done by
2274 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2275 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002276 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002277 mKeepaliveTracker.handleStopAllKeepalives(nai,
2278 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002279 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2280 // Disable wakeup packet monitoring for each interface.
2281 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2282 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002283 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002284 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichi37119102017-08-31 14:32:54 +00002285 maybeStopClat(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002286 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002287 // Remove the NetworkAgent, but don't mark the netId as
2288 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002289 mNetworkForNetId.remove(nai.network.netId);
2290 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002291 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002292 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2293 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002294 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2295 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2296 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002297 sendUpdatedScoreToFactories(request, 0);
2298 }
2299 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002300 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002301 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002302 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002303 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002304 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002305 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002306 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002307 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002308 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002309 if (nai.created) {
2310 // Tell netd to clean up the configuration for this network
2311 // (routing rules, DNS, etc).
2312 // This may be slow as it requires a lot of netd shelling out to ip and
2313 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2314 // after we've rematched networks with requests which should make a potential
2315 // fallback network the default or requested a new network from the
2316 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2317 // long time.
2318 try {
2319 mNetd.removeNetwork(nai.network.netId);
2320 } catch (Exception e) {
2321 loge("Exception removing network: " + e);
2322 }
2323 }
2324 synchronized (mNetworkForNetId) {
2325 mNetIdInUse.delete(nai.network.netId);
2326 }
2327 } else {
2328 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2329 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002330 }
2331 }
2332
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002333 // If this method proves to be too slow then we can maintain a separate
2334 // pendingIntent => NetworkRequestInfo map.
2335 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2336 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2337 Intent intent = pendingIntent.getIntent();
2338 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2339 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2340 if (existingPendingIntent != null &&
2341 existingPendingIntent.getIntent().filterEquals(intent)) {
2342 return entry.getValue();
2343 }
2344 }
2345 return null;
2346 }
2347
2348 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2349 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2350
2351 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2352 if (existingRequest != null) { // remove the existing request.
2353 if (DBG) log("Replacing " + existingRequest.request + " with "
2354 + nri.request + " because their intents matched.");
2355 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2356 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002357 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002358 }
2359
Erik Klineda4bfa82015-04-30 12:58:40 +09002360 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002361 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002362 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002363 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002364 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002365 if (nri.request.networkCapabilities.hasSignalStrength() &&
2366 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2367 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002368 }
2369 }
2370 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002371 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002372 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002373 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002374 }
2375 }
2376
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002377 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2378 int callingUid) {
2379 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2380 if (nri != null) {
2381 handleReleaseNetworkRequest(nri.request, callingUid);
2382 }
2383 }
2384
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002385 // Determines whether the network is the best (or could become the best, if it validated), for
2386 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2387 // on the value of reason:
2388 //
2389 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2390 // then it should be torn down.
2391 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2392 // then it should be lingered.
2393 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2394 final int numRequests;
2395 switch (reason) {
2396 case TEARDOWN:
2397 numRequests = nai.numRequestNetworkRequests();
2398 break;
2399 case LINGER:
2400 numRequests = nai.numForegroundNetworkRequests();
2401 break;
2402 default:
2403 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2404 return true;
2405 }
2406
2407 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002408 return false;
2409 }
Paul Jensene0988542015-06-25 15:30:08 -04002410 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002411 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2412 // Background requests don't affect lingering.
2413 continue;
2414 }
2415
Paul Jensene0988542015-06-25 15:30:08 -04002416 // If this Network is already the highest scoring Network for a request, or if
2417 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002418 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002419 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002420 // Note that this catches two important cases:
2421 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2422 // is currently satisfying the request. This is desirable when
2423 // cellular ends up validating but WiFi does not.
2424 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002425 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002426 // WiFi ends up validating and out scoring cellular.
2427 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2428 nai.getCurrentScoreAsValidated())) {
2429 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002430 }
2431 }
Paul Jensene0988542015-06-25 15:30:08 -04002432 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002433 }
2434
Erik Klineacdd6392016-07-07 16:50:58 +09002435 private NetworkRequestInfo getNriForAppRequest(
2436 NetworkRequest request, int callingUid, String requestedOperation) {
2437 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2438
Robert Greenwalt9258c642014-03-26 16:47:06 -07002439 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002440 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002441 log(String.format("UID %d attempted to %s for unowned request %s",
2442 callingUid, requestedOperation, nri));
2443 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002444 }
Erik Klineacdd6392016-07-07 16:50:58 +09002445 }
2446
2447 return nri;
2448 }
2449
Erik Kline57faba92015-11-25 12:49:38 +09002450 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002451 if (mNetworkRequests.get(nri.request) == null) {
2452 return;
Erik Kline57faba92015-11-25 12:49:38 +09002453 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002454 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2455 return;
2456 }
2457 if (VDBG || (DBG && nri.request.isRequest())) {
2458 log("releasing " + nri.request + " (timeout)");
2459 }
2460 handleRemoveNetworkRequest(nri);
2461 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002462 }
2463
Erik Klineacdd6392016-07-07 16:50:58 +09002464 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002465 final NetworkRequestInfo nri =
2466 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2467 if (nri == null) {
2468 return;
Erik Kline57faba92015-11-25 12:49:38 +09002469 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002470 if (VDBG || (DBG && nri.request.isRequest())) {
2471 log("releasing " + nri.request + " (release request)");
2472 }
2473 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002474 }
Erik Klineacdd6392016-07-07 16:50:58 +09002475
Hugo Benichidba33db2017-03-23 22:40:44 +09002476 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002477 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002478 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002479 synchronized (mUidToNetworkRequestCount) {
2480 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2481 if (requests < 1) {
2482 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2483 nri.mUid);
2484 } else if (requests == 1) {
2485 mUidToNetworkRequestCount.removeAt(
2486 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2487 } else {
2488 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2489 }
2490 }
2491 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2492 if (nri.request.isRequest()) {
2493 boolean wasKept = false;
2494 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2495 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002496 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002497 nai.removeRequest(nri.request.requestId);
2498 if (VDBG) {
2499 log(" Removing from current network " + nai.name() +
2500 ", leaving " + nai.numNetworkRequests() + " requests.");
2501 }
2502 // If there are still lingered requests on this network, don't tear it down,
2503 // but resume lingering instead.
2504 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002505 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002506 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2507 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002508 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002509 wasKept = true;
2510 }
2511 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002512 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2513 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002514 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002515 }
Erik Klineacdd6392016-07-07 16:50:58 +09002516 }
2517
2518 // TODO: remove this code once we know that the Slog.wtf is never hit.
2519 //
2520 // Find all networks that are satisfying this request and remove the request
2521 // from their request lists.
2522 // TODO - it's my understanding that for a request there is only a single
2523 // network satisfying it, so this loop is wasteful
2524 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2525 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2526 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2527 otherNai.name() + ", but mNetworkAgentInfos says " +
2528 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002529 }
2530 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002531
Erik Klineacdd6392016-07-07 16:50:58 +09002532 // Maintain the illusion. When this request arrived, we might have pretended
2533 // that a network connected to serve it, even though the network was already
2534 // connected. Now that this request has gone away, we might have to pretend
2535 // that the network disconnected. LegacyTypeTracker will generate that
2536 // phantom disconnect for this type.
2537 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2538 boolean doRemove = true;
2539 if (wasKept) {
2540 // check if any of the remaining requests for this network are for the
2541 // same legacy type - if so, don't remove the nai
2542 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2543 NetworkRequest otherRequest = nai.requestAt(i);
2544 if (otherRequest.legacyType == nri.request.legacyType &&
2545 otherRequest.isRequest()) {
2546 if (DBG) log(" still have other legacy request - leaving");
2547 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002548 }
2549 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002550 }
2551
Erik Klineacdd6392016-07-07 16:50:58 +09002552 if (doRemove) {
2553 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002554 }
2555 }
Erik Klineacdd6392016-07-07 16:50:58 +09002556
2557 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2558 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2559 nri.request);
2560 }
2561 } else {
2562 // listens don't have a singular affectedNetwork. Check all networks to see
2563 // if this listen request applies and remove it.
2564 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2565 nai.removeRequest(nri.request.requestId);
2566 if (nri.request.networkCapabilities.hasSignalStrength() &&
2567 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2568 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2569 }
2570 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002571 }
2572 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002573
Lorenzo Colitti18660282016-07-04 12:55:44 +09002574 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002575 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2576 enforceConnectivityInternalPermission();
2577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002578 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002579 }
2580
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002581 @Override
2582 public void setAvoidUnvalidated(Network network) {
2583 enforceConnectivityInternalPermission();
2584 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2585 }
2586
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002587 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2588 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2589 " accept=" + accept + " always=" + always);
2590
2591 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2592 if (nai == null) {
2593 // Nothing to do.
2594 return;
2595 }
2596
2597 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002598 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002599 return;
2600 }
2601
2602 if (!nai.networkMisc.explicitlySelected) {
2603 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2604 }
2605
2606 if (accept != nai.networkMisc.acceptUnvalidated) {
2607 int oldScore = nai.getCurrentScore();
2608 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002609 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002610 sendUpdatedScoreToFactories(nai);
2611 }
2612
2613 if (always) {
2614 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002615 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002616 }
2617
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002618 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002619 // Tell the NetworkAgent to not automatically reconnect to the network.
2620 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2621 // Teardown the nework.
2622 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002623 }
2624
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002625 }
2626
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002627 private void handleSetAvoidUnvalidated(Network network) {
2628 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2629 if (nai == null || nai.lastValidated) {
2630 // Nothing to do. The network either disconnected or revalidated.
2631 return;
2632 }
2633 if (!nai.avoidUnvalidated) {
2634 int oldScore = nai.getCurrentScore();
2635 nai.avoidUnvalidated = true;
2636 rematchAllNetworksAndRequests(nai, oldScore);
2637 sendUpdatedScoreToFactories(nai);
2638 }
2639 }
2640
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002641 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002642 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002643 mHandler.sendMessageDelayed(
2644 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2645 PROMPT_UNVALIDATED_DELAY_MS);
2646 }
2647
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002648 @Override
2649 public void startCaptivePortalApp(Network network) {
2650 enforceConnectivityInternalPermission();
2651 mHandler.post(() -> {
2652 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2653 if (nai == null) return;
2654 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2655 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2656 });
2657 }
2658
Hugo Benichic8e9e122016-09-14 23:23:08 +00002659 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002660 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002661 }
2662
Erik Kline065ab6e2016-10-02 18:02:14 +09002663 private void rematchForAvoidBadWifiUpdate() {
2664 rematchAllNetworksAndRequests(null, 0);
2665 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2666 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2667 sendUpdatedScoreToFactories(nai);
2668 }
2669 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002670 }
2671
Erik Kline065ab6e2016-10-02 18:02:14 +09002672 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002673 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002674 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002675 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002676 if (!configRestrict) {
2677 pw.println("Bad Wi-Fi avoidance: unrestricted");
2678 return;
2679 }
2680
2681 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2682 pw.increaseIndent();
2683 pw.println("Config restrict: " + configRestrict);
2684
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002685 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002686 String description;
2687 // Can't use a switch statement because strings are legal case labels, but null is not.
2688 if ("0".equals(value)) {
2689 description = "get stuck";
2690 } else if (value == null) {
2691 description = "prompt";
2692 } else if ("1".equals(value)) {
2693 description = "avoid";
2694 } else {
2695 description = value + " (?)";
2696 }
2697 pw.println("User setting: " + description);
2698 pw.println("Network overrides:");
2699 pw.increaseIndent();
2700 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2701 if (nai.avoidUnvalidated) {
2702 pw.println(nai.name());
2703 }
2704 }
2705 pw.decreaseIndent();
2706 pw.decreaseIndent();
2707 }
2708
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002709 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2710 final String action;
2711 switch (type) {
2712 case NO_INTERNET:
2713 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2714 break;
2715 case LOST_INTERNET:
2716 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2717 break;
2718 default:
2719 Slog.wtf(TAG, "Unknown notification type " + type);
2720 return;
2721 }
2722
2723 Intent intent = new Intent(action);
2724 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2725 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2726 intent.setClassName("com.android.settings",
2727 "com.android.settings.wifi.WifiNoInternetDialog");
2728
2729 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2730 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2731 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2732 }
2733
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002734 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002735 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002736 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2737
2738 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2739 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002740 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002741 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002742 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2743 return;
2744 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002745 showValidationNotification(nai, NotificationType.NO_INTERNET);
2746 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002747
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002748 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2749 NetworkCapabilities nc = nai.networkCapabilities;
2750 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002751
Erik Kline065ab6e2016-10-02 18:02:14 +09002752 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002753 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002754 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2755 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002756 }
2757
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002758 @Override
2759 public int getMultipathPreference(Network network) {
2760 enforceAccessPermission();
2761
2762 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002763 if (nai != null && nai.networkCapabilities
2764 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002765 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2766 }
2767
2768 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2769 }
2770
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002771 private class InternalHandler extends Handler {
2772 public InternalHandler(Looper looper) {
2773 super(looper);
2774 }
2775
2776 @Override
2777 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002778 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002779 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002780 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002781 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002782 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002783 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002784 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002785 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002786 break;
2787 }
Jason Monkdecd2952013-10-10 14:02:51 -04002788 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002789 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002790 break;
2791 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002792 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002793 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2794 break;
2795 }
2796 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2797 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002798 break;
2799 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002800 case EVENT_REGISTER_NETWORK_AGENT: {
2801 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2802 break;
2803 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002804 case EVENT_REGISTER_NETWORK_REQUEST:
2805 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002806 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002807 break;
2808 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002809 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2810 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002811 handleRegisterNetworkRequestWithIntent(msg);
2812 break;
2813 }
Erik Kline57faba92015-11-25 12:49:38 +09002814 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2815 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2816 handleTimedOutNetworkRequest(nri);
2817 break;
2818 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002819 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2820 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2821 break;
2822 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002823 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002824 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002825 break;
2826 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002827 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002828 Network network = (Network) msg.obj;
2829 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002830 break;
2831 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002832 case EVENT_SET_AVOID_UNVALIDATED: {
2833 handleSetAvoidUnvalidated((Network) msg.obj);
2834 break;
2835 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002836 case EVENT_PROMPT_UNVALIDATED: {
2837 handlePromptUnvalidated((Network) msg.obj);
2838 break;
2839 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002840 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2841 handleMobileDataAlwaysOn();
2842 break;
2843 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002844 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2845 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2846 mKeepaliveTracker.handleStartKeepalive(msg);
2847 break;
2848 }
2849 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2850 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2851 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2852 int slot = msg.arg1;
2853 int reason = msg.arg2;
2854 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2855 break;
2856 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002857 case EVENT_SYSTEM_READY: {
2858 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2859 nai.networkMonitor.systemReady = true;
2860 }
2861 break;
2862 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002863 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002864 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002865 break;
2866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
2868 }
2869 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002870
2871 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002872 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002873 public int tether(String iface, String callerPkg) {
2874 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002875 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002876 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002877 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002878 } else {
2879 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2880 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002881 }
2882
2883 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002884 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002885 public int untether(String iface, String callerPkg) {
2886 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002887
2888 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002889 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002890 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002891 } else {
2892 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2893 }
2894 }
2895
2896 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002897 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002898 public int getLastTetherError(String iface) {
2899 enforceTetherAccessPermission();
2900
2901 if (isTetheringSupported()) {
2902 return mTethering.getLastTetherError(iface);
2903 } else {
2904 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2905 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002906 }
2907
2908 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002909 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002910 public String[] getTetherableUsbRegexs() {
2911 enforceTetherAccessPermission();
2912 if (isTetheringSupported()) {
2913 return mTethering.getTetherableUsbRegexs();
2914 } else {
2915 return new String[0];
2916 }
2917 }
2918
Lorenzo Colitti18660282016-07-04 12:55:44 +09002919 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002920 public String[] getTetherableWifiRegexs() {
2921 enforceTetherAccessPermission();
2922 if (isTetheringSupported()) {
2923 return mTethering.getTetherableWifiRegexs();
2924 } else {
2925 return new String[0];
2926 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002927 }
2928
Lorenzo Colitti18660282016-07-04 12:55:44 +09002929 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002930 public String[] getTetherableBluetoothRegexs() {
2931 enforceTetherAccessPermission();
2932 if (isTetheringSupported()) {
2933 return mTethering.getTetherableBluetoothRegexs();
2934 } else {
2935 return new String[0];
2936 }
2937 }
2938
Lorenzo Colitti18660282016-07-04 12:55:44 +09002939 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002940 public int setUsbTethering(boolean enable, String callerPkg) {
2941 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002942 if (isTetheringSupported()) {
2943 return mTethering.setUsbTethering(enable);
2944 } else {
2945 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2946 }
2947 }
2948
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002949 // TODO - move iface listing, queries, etc to new module
2950 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002951 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002952 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002953 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002954 return mTethering.getTetherableIfaces();
2955 }
2956
Lorenzo Colitti18660282016-07-04 12:55:44 +09002957 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002958 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002959 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002960 return mTethering.getTetheredIfaces();
2961 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002962
Lorenzo Colitti18660282016-07-04 12:55:44 +09002963 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002964 public String[] getTetheringErroredIfaces() {
2965 enforceTetherAccessPermission();
2966 return mTethering.getErroredIfaces();
2967 }
2968
Lorenzo Colitti18660282016-07-04 12:55:44 +09002969 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002970 public String[] getTetheredDhcpRanges() {
2971 enforceConnectivityInternalPermission();
2972 return mTethering.getTetheredDhcpRanges();
2973 }
2974
Udam Saini0e94c362017-06-07 12:06:28 -07002975 @Override
2976 public boolean isTetheringSupported(String callerPkg) {
2977 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
2978 return isTetheringSupported();
2979 }
2980
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002981 // if ro.tether.denied = true we default to no tethering
2982 // gservices could set the secure setting to 1 though to enable it on a build where it
2983 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07002984 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002985 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2986 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2987 Settings.Global.TETHER_SUPPORTED, defaultVal));
2988 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002989 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002990
2991 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2992 boolean adminUser = false;
2993 final long token = Binder.clearCallingIdentity();
2994 try {
2995 adminUser = mUserManager.isAdminUser();
2996 } finally {
2997 Binder.restoreCallingIdentity(token);
2998 }
2999
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003000 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003001 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003002
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003003 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003004 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3005 String callerPkg) {
3006 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003007 if (!isTetheringSupported()) {
3008 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3009 return;
3010 }
3011 mTethering.startTethering(type, receiver, showProvisioningUi);
3012 }
3013
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003014 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003015 public void stopTethering(int type, String callerPkg) {
3016 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003017 mTethering.stopTethering(type);
3018 }
3019
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003020 // Called when we lose the default network and have no replacement yet.
3021 // This will automatically be cleared after X seconds or a new default network
3022 // becomes CONNECTED, whichever happens first. The timer is started by the
3023 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003024 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003025 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003026 if (mNetTransitionWakeLock.isHeld()) {
3027 return;
3028 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003029 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003030 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3031 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003032 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003033 mWakelockLogs.log("ACQUIRE for " + forWhom);
3034 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3035 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003036 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003037
Hugo Benichi4c31b342017-03-30 23:18:10 +09003038 // Called when we gain a new default network to release the network transition wakelock in a
3039 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3040 // message is cancelled.
3041 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003042 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003043 if (!mNetTransitionWakeLock.isHeld()) {
3044 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003045 }
3046 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003047 // Cancel self timeout on wakelock hold.
3048 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3049 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3050 mHandler.sendMessageDelayed(msg, 1000);
3051 }
3052
3053 // Called when either message of ensureNetworkTransitionWakelock or
3054 // scheduleReleaseNetworkTransitionWakelock is processed.
3055 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3056 String event = eventName(eventId);
3057 synchronized (this) {
3058 if (!mNetTransitionWakeLock.isHeld()) {
3059 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3060 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3061 return;
3062 }
3063 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003064 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3065 mTotalWakelockDurationMs += lockDuration;
3066 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3067 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003068 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003069 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003070 }
3071
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003072 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003074 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003075 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003076 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003077 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003078 }
3079
Lorenzo Colitti18660282016-07-04 12:55:44 +09003080 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003081 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003082 enforceAccessPermission();
3083 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003084 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003085 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003086 mHandler.sendMessage(
3087 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3088 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003089
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003090 private void handleReportNetworkConnectivity(
3091 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003092 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003093 if (network == null) {
3094 nai = getDefaultNetwork();
3095 } else {
3096 nai = getNetworkAgentInfoForNetwork(network);
3097 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003098 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3099 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3100 return;
3101 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003102 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003103 if (hasConnectivity == nai.lastValidated) {
3104 return;
3105 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003106 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003107 int netid = nai.network.netId;
3108 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003109 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003110 // Validating a network that has not yet connected could result in a call to
3111 // rematchNetworkAndRequests() which is not meant to work on such networks.
3112 if (!nai.everConnected) {
3113 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003114 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003115 LinkProperties lp = getLinkProperties(nai);
3116 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3117 return;
3118 }
3119 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003120 }
3121
Paul Jensencee9b512015-05-06 07:32:40 -04003122 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003123 // this information is already available as a world read/writable jvm property
3124 // so this API change wouldn't have a benifit. It also breaks the passing
3125 // of proxy info to all the JVMs.
3126 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003127 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003128 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003129 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3130 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003131 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003132 }
3133
Lorenzo Colitti18660282016-07-04 12:55:44 +09003134 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003135 public ProxyInfo getProxyForNetwork(Network network) {
3136 if (network == null) return getDefaultProxy();
3137 final ProxyInfo globalProxy = getGlobalProxy();
3138 if (globalProxy != null) return globalProxy;
3139 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3140 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3141 // caller may not have.
3142 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3143 if (nai == null) return null;
3144 synchronized (nai) {
3145 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3146 if (proxyInfo == null) return null;
3147 return new ProxyInfo(proxyInfo);
3148 }
3149 }
3150
Paul Jensene0bef712014-12-10 15:12:18 -05003151 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3152 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3153 // proxy is null then there is no proxy in place).
3154 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3155 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3156 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3157 proxy = null;
3158 }
3159 return proxy;
3160 }
3161
3162 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3163 // better for determining if a new proxy broadcast is necessary:
3164 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3165 // avoid unnecessary broadcasts.
3166 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3167 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3168 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3169 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3170 // all set.
3171 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3172 a = canonicalizeProxyInfo(a);
3173 b = canonicalizeProxyInfo(b);
3174 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3175 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3176 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3177 }
3178
Jason Monk207900c2014-04-25 15:00:09 -04003179 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003180 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003181
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003182 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003183 if (proxyProperties == mGlobalProxy) return;
3184 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3185 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3186
3187 String host = "";
3188 int port = 0;
3189 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003190 String pacFileUrl = "";
3191 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003192 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003193 if (!proxyProperties.isValid()) {
3194 if (DBG)
3195 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3196 return;
3197 }
Jason Monk207900c2014-04-25 15:00:09 -04003198 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003199 host = mGlobalProxy.getHost();
3200 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003201 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003202 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003203 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003204 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003205 } else {
3206 mGlobalProxy = null;
3207 }
3208 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003209 final long token = Binder.clearCallingIdentity();
3210 try {
3211 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3212 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3213 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3214 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003215 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003216 } finally {
3217 Binder.restoreCallingIdentity(token);
3218 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003219
Jason Monkcf0f97a2014-10-02 15:39:38 -04003220 if (mGlobalProxy == null) {
3221 proxyProperties = mDefaultProxy;
3222 }
3223 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003224 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003225 }
3226
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003227 private void loadGlobalProxy() {
3228 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003229 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3230 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3231 String exclList = Settings.Global.getString(res,
3232 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003233 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3234 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003235 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003236 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003237 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003238 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003239 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003240 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003241 if (!proxyProperties.isValid()) {
3242 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3243 return;
3244 }
3245
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003246 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003247 mGlobalProxy = proxyProperties;
3248 }
3249 }
3250 }
3251
Jason Monk207900c2014-04-25 15:00:09 -04003252 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003253 // this information is already available as a world read/writable jvm property
3254 // so this API change wouldn't have a benifit. It also breaks the passing
3255 // of proxy info to all the JVMs.
3256 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003257 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003258 return mGlobalProxy;
3259 }
3260 }
3261
Jason Monk207900c2014-04-25 15:00:09 -04003262 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003263 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003264 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003265 proxy = null;
3266 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003267 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003269 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003270 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003271 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3272 return;
3273 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003274
3275 // This call could be coming from the PacManager, containing the port of the local
3276 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3277 // global (to get the correct local port), and send a broadcast.
3278 // TODO: Switch PacManager to have its own message to send back rather than
3279 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003280 if ((mGlobalProxy != null) && (proxy != null)
3281 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003282 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3283 mGlobalProxy = proxy;
3284 sendProxyBroadcast(mGlobalProxy);
3285 return;
3286 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003287 mDefaultProxy = proxy;
3288
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003290 if (!mDefaultProxyDisabled) {
3291 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003292 }
3293 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 }
3295
Paul Jensene0bef712014-12-10 15:12:18 -05003296 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3297 // This method gets called when any network changes proxy, but the broadcast only ever contains
3298 // the default proxy (even if it hasn't changed).
3299 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3300 // world where an app might be bound to a non-default network.
3301 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3302 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3303 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3304
3305 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3306 sendProxyBroadcast(getDefaultProxy());
3307 }
3308 }
3309
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003311 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3312 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 if (!TextUtils.isEmpty(proxy)) {
3314 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003315 if (data.length == 0) {
3316 return;
3317 }
3318
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319 String proxyHost = data[0];
3320 int proxyPort = 8080;
3321 if (data.length > 1) {
3322 try {
3323 proxyPort = Integer.parseInt(data[1]);
3324 } catch (NumberFormatException e) {
3325 return;
3326 }
3327 }
Jason Monk207900c2014-04-25 15:00:09 -04003328 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003329 setGlobalProxy(p);
3330 }
3331 }
3332
Jason Monk207900c2014-04-25 15:00:09 -04003333 private void sendProxyBroadcast(ProxyInfo proxy) {
3334 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003335 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003336 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003337 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003338 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3339 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003340 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003341 final long ident = Binder.clearCallingIdentity();
3342 try {
3343 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3344 } finally {
3345 Binder.restoreCallingIdentity(ident);
3346 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003347 }
3348
3349 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003350 final private HashMap<Uri, Integer> mUriEventMap;
3351 final private Context mContext;
3352 final private Handler mHandler;
3353
3354 SettingsObserver(Context context, Handler handler) {
3355 super(null);
3356 mUriEventMap = new HashMap<Uri, Integer>();
3357 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003358 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 }
3360
Erik Klineda4bfa82015-04-30 12:58:40 +09003361 void observe(Uri uri, int what) {
3362 mUriEventMap.put(uri, what);
3363 final ContentResolver resolver = mContext.getContentResolver();
3364 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003365 }
3366
3367 @Override
3368 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003369 Slog.wtf(TAG, "Should never be reached.");
3370 }
3371
3372 @Override
3373 public void onChange(boolean selfChange, Uri uri) {
3374 final Integer what = mUriEventMap.get(uri);
3375 if (what != null) {
3376 mHandler.obtainMessage(what.intValue()).sendToTarget();
3377 } else {
3378 loge("No matching event to send for URI=" + uri);
3379 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003380 }
3381 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003382
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003383 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003384 Slog.d(TAG, s);
3385 }
3386
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003387 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003388 Slog.e(TAG, s);
3389 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003390
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003391 private static void loge(String s, Throwable t) {
3392 Slog.e(TAG, s, t);
3393 }
3394
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003395 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003396 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003397 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3398 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3399 *
3400 * @param oldPackage Package name of the application which currently controls VPN, which will
3401 * be replaced. If there is no such application, this should should either be
3402 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3403 * @param newPackage Package name of the application which should gain control of VPN, or
3404 * {@code null} to disable.
3405 * @param userId User for whom to prepare the new VPN.
3406 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003407 * @hide
3408 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003409 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003410 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3411 int userId) {
3412 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003413 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003414
Hugo Benichi20035e02017-04-26 14:53:28 +09003415 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003416 Vpn vpn = mVpns.get(userId);
3417 if (vpn != null) {
3418 return vpn.prepare(oldPackage, newPackage);
3419 } else {
3420 return false;
3421 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003422 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003423 }
3424
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003425 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003426 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3427 * This method is used by system-privileged apps.
3428 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3429 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3430 *
3431 * @param packageName The package for which authorization state should change.
3432 * @param userId User for whom {@code packageName} is installed.
3433 * @param authorized {@code true} if this app should be able to start a VPN connection without
3434 * explicit user approval, {@code false} if not.
3435 *
Jeff Davidson05542602014-08-11 14:07:27 -07003436 * @hide
3437 */
3438 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003439 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3440 enforceCrossUserPermission(userId);
3441
Hugo Benichi20035e02017-04-26 14:53:28 +09003442 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003443 Vpn vpn = mVpns.get(userId);
3444 if (vpn != null) {
3445 vpn.setPackageAuthorization(packageName, authorized);
3446 }
Jeff Davidson05542602014-08-11 14:07:27 -07003447 }
3448 }
3449
3450 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003451 * Configure a TUN interface and return its file descriptor. Parameters
3452 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003453 * and not available in ConnectivityManager. Permissions are checked in
3454 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003455 * @hide
3456 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003457 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003458 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003459 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003460 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003461 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003462 return mVpns.get(user).establish(config);
3463 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003464 }
3465
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003466 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003467 * Start legacy VPN, controlling native daemons as needed. Creates a
3468 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003469 */
3470 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003471 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003472 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003473 final LinkProperties egress = getActiveLinkProperties();
3474 if (egress == null) {
3475 throw new IllegalStateException("Missing active network connection");
3476 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003477 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003478 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003479 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3480 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003481 }
3482
3483 /**
3484 * Return the information of the ongoing legacy VPN. This method is used
3485 * by VpnSettings and not available in ConnectivityManager. Permissions
3486 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003487 */
3488 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003489 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3490 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003491
Hugo Benichi20035e02017-04-26 14:53:28 +09003492 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003493 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003494 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003495 }
3496
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003497 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003498 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3499 * and not available in ConnectivityManager.
3500 */
3501 @Override
3502 public VpnInfo[] getAllVpnInfo() {
3503 enforceConnectivityInternalPermission();
3504 if (mLockdownEnabled) {
3505 return new VpnInfo[0];
3506 }
3507
Hugo Benichi20035e02017-04-26 14:53:28 +09003508 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003509 List<VpnInfo> infoList = new ArrayList<>();
3510 for (int i = 0; i < mVpns.size(); i++) {
3511 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3512 if (info != null) {
3513 infoList.add(info);
3514 }
3515 }
3516 return infoList.toArray(new VpnInfo[infoList.size()]);
3517 }
3518 }
3519
3520 /**
3521 * @return VPN information for accounting, or null if we can't retrieve all required
3522 * information, e.g primary underlying iface.
3523 */
3524 @Nullable
3525 private VpnInfo createVpnInfo(Vpn vpn) {
3526 VpnInfo info = vpn.getVpnInfo();
3527 if (info == null) {
3528 return null;
3529 }
3530 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3531 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3532 // the underlyingNetworks list.
3533 if (underlyingNetworks == null) {
3534 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3535 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3536 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3537 }
3538 } else if (underlyingNetworks.length > 0) {
3539 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3540 if (linkProperties != null) {
3541 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3542 }
3543 }
3544 return info.primaryUnderlyingIface == null ? null : info;
3545 }
3546
3547 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003548 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3549 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003550 * Permissions are checked in Vpn class.
3551 * @hide
3552 */
3553 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003554 public VpnConfig getVpnConfig(int userId) {
3555 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003556 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003557 Vpn vpn = mVpns.get(userId);
3558 if (vpn != null) {
3559 return vpn.getVpnConfig();
3560 } else {
3561 return null;
3562 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003563 }
3564 }
3565
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003566 @Override
3567 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003568 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3569 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3570 return false;
3571 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003572
3573 // Tear down existing lockdown if profile was removed
3574 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3575 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003576 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3577 if (profileTag == null) {
3578 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3579 return false;
3580 }
3581 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003582 final VpnProfile profile = VpnProfile.decode(
3583 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003584 if (profile == null) {
3585 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3586 setLockdownTracker(null);
3587 return true;
3588 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003589 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003590 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003591 Vpn vpn = mVpns.get(user);
3592 if (vpn == null) {
3593 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3594 return false;
3595 }
3596 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003597 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003598 } else {
3599 setLockdownTracker(null);
3600 }
3601
3602 return true;
3603 }
3604
3605 /**
3606 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3607 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3608 */
3609 private void setLockdownTracker(LockdownVpnTracker tracker) {
3610 // Shutdown any existing tracker
3611 final LockdownVpnTracker existing = mLockdownTracker;
3612 mLockdownTracker = null;
3613 if (existing != null) {
3614 existing.shutdown();
3615 }
3616
Robin Leec3736bc2017-03-10 16:19:54 +00003617 if (tracker != null) {
3618 mLockdownTracker = tracker;
3619 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003620 }
3621 }
3622
3623 private void throwIfLockdownEnabled() {
3624 if (mLockdownEnabled) {
3625 throw new IllegalStateException("Unavailable in lockdown mode");
3626 }
3627 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003628
Robin Lee244ce8e2016-01-05 18:03:46 +00003629 /**
Robin Lee17e61832016-05-09 13:46:28 +01003630 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3631 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003632 *
Robin Lee17e61832016-05-09 13:46:28 +01003633 * @return {@code true} if the service was started, the service was already connected, or there
3634 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003635 */
Robin Lee17e61832016-05-09 13:46:28 +01003636 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003637 synchronized (mVpns) {
3638 Vpn vpn = mVpns.get(userId);
3639 if (vpn == null) {
3640 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3641 // exists already.
3642 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3643 return false;
3644 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003645
Robin Lee812800c2016-05-13 15:38:08 +01003646 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003647 }
3648 }
3649
3650 @Override
Charles He36738632017-05-15 17:07:18 +01003651 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3652 enforceSettingsPermission();
3653 enforceCrossUserPermission(userId);
3654
3655 synchronized (mVpns) {
3656 Vpn vpn = mVpns.get(userId);
3657 if (vpn == null) {
3658 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3659 return false;
3660 }
3661 return vpn.isAlwaysOnPackageSupported(packageName);
3662 }
3663 }
3664
3665 @Override
Robin Leedc679712016-05-03 13:23:03 +01003666 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003667 enforceConnectivityInternalPermission();
3668 enforceCrossUserPermission(userId);
3669
3670 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3671 if (LockdownVpnTracker.isEnabled()) {
3672 return false;
3673 }
3674
Robin Lee244ce8e2016-01-05 18:03:46 +00003675 synchronized (mVpns) {
3676 Vpn vpn = mVpns.get(userId);
3677 if (vpn == null) {
3678 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3679 return false;
3680 }
Robin Lee17e61832016-05-09 13:46:28 +01003681 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003682 return false;
3683 }
Robin Lee17e61832016-05-09 13:46:28 +01003684 if (!startAlwaysOnVpn(userId)) {
3685 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003686 return false;
3687 }
3688 }
3689 return true;
3690 }
3691
3692 @Override
3693 public String getAlwaysOnVpnPackage(int userId) {
3694 enforceConnectivityInternalPermission();
3695 enforceCrossUserPermission(userId);
3696
3697 synchronized (mVpns) {
3698 Vpn vpn = mVpns.get(userId);
3699 if (vpn == null) {
3700 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3701 return null;
3702 }
3703 return vpn.getAlwaysOnPackage();
3704 }
3705 }
3706
Wink Savilleab9321d2013-06-29 21:10:57 -07003707 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003708 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003709 // TODO: Remove? Any reason to trigger a provisioning check?
3710 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003711 }
3712
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003713 /** Location to an updatable file listing carrier provisioning urls.
3714 * An example:
3715 *
3716 * <?xml version="1.0" encoding="utf-8"?>
3717 * <provisioningUrls>
3718 * <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 -07003719 * </provisioningUrls>
3720 */
3721 private static final String PROVISIONING_URL_PATH =
3722 "/data/misc/radio/provisioning_urls.xml";
3723 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003724
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003725 /** XML tag for root element. */
3726 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3727 /** XML tag for individual url */
3728 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003729 /** XML attribute for mcc */
3730 private static final String ATTR_MCC = "mcc";
3731 /** XML attribute for mnc */
3732 private static final String ATTR_MNC = "mnc";
3733
Paul Jensen434dde82015-06-11 09:43:30 -04003734 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003735 FileReader fileReader = null;
3736 XmlPullParser parser = null;
3737 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003738
3739 try {
3740 fileReader = new FileReader(mProvisioningUrlFile);
3741 parser = Xml.newPullParser();
3742 parser.setInput(fileReader);
3743 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3744
3745 while (true) {
3746 XmlUtils.nextElement(parser);
3747
3748 String element = parser.getName();
3749 if (element == null) break;
3750
Paul Jensen434dde82015-06-11 09:43:30 -04003751 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003752 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3753 try {
3754 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3755 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3756 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3757 parser.next();
3758 if (parser.getEventType() == XmlPullParser.TEXT) {
3759 return parser.getText();
3760 }
3761 }
3762 }
3763 } catch (NumberFormatException e) {
3764 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3765 }
3766 }
3767 }
3768 return null;
3769 } catch (FileNotFoundException e) {
3770 loge("Carrier Provisioning Urls file not found");
3771 } catch (XmlPullParserException e) {
3772 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3773 } catch (IOException e) {
3774 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3775 } finally {
3776 if (fileReader != null) {
3777 try {
3778 fileReader.close();
3779 } catch (IOException e) {}
3780 }
3781 }
3782 return null;
3783 }
3784
Wink Saville42d4f082013-07-20 20:31:59 -07003785 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003786 public String getMobileProvisioningUrl() {
3787 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003788 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003789 if (TextUtils.isEmpty(url)) {
3790 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003791 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003792 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003793 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003794 }
Wink Saville8cf35602013-07-10 23:00:07 -07003795 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003796 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003797 String phoneNumber = mTelephonyManager.getLine1Number();
3798 if (TextUtils.isEmpty(phoneNumber)) {
3799 phoneNumber = "0000000000";
3800 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003801 url = String.format(url,
3802 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3803 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003804 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003805 }
3806
Wink Savilleab9321d2013-06-29 21:10:57 -07003807 return url;
3808 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003809
Wink Saville948282b2013-08-29 08:55:16 -07003810 @Override
3811 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003812 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003813 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003814 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3815 return;
3816 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003817 final long ident = Binder.clearCallingIdentity();
3818 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003819 // Concatenate the range of types onto the range of NetIDs.
3820 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3821 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003822 } finally {
3823 Binder.restoreCallingIdentity(ident);
3824 }
Wink Saville948282b2013-08-29 08:55:16 -07003825 }
Wink Saville7788c612013-08-29 14:57:08 -07003826
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003827 @Override
3828 public void setAirplaneMode(boolean enable) {
3829 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003830 final long ident = Binder.clearCallingIdentity();
3831 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003832 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003833 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003834 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3835 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003836 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003837 } finally {
3838 Binder.restoreCallingIdentity(ident);
3839 }
3840 }
3841
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003842 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003843 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003844 Vpn userVpn = mVpns.get(userId);
3845 if (userVpn != null) {
3846 loge("Starting user already has a VPN");
3847 return;
3848 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003849 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003850 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003851 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003852 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3853 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003854 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003855 }
3856
3857 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003858 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003859 Vpn userVpn = mVpns.get(userId);
3860 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003861 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003862 return;
3863 }
Robin Lee17e61832016-05-09 13:46:28 +01003864 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003865 mVpns.delete(userId);
3866 }
3867 }
3868
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003869 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003870 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003871 final int vpnsSize = mVpns.size();
3872 for (int i = 0; i < vpnsSize; i++) {
3873 Vpn vpn = mVpns.valueAt(i);
3874 vpn.onUserAdded(userId);
3875 }
3876 }
3877 }
3878
3879 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003880 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003881 final int vpnsSize = mVpns.size();
3882 for (int i = 0; i < vpnsSize; i++) {
3883 Vpn vpn = mVpns.valueAt(i);
3884 vpn.onUserRemoved(userId);
3885 }
3886 }
3887 }
3888
Robin Lee89e7a692016-02-29 14:38:17 +00003889 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003890 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3891 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3892 updateLockdownVpn();
3893 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003894 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003895 }
3896 }
3897
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003898 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3899 @Override
3900 public void onReceive(Context context, Intent intent) {
3901 final String action = intent.getAction();
3902 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3903 if (userId == UserHandle.USER_NULL) return;
3904
Robin Lee323f29d2016-05-04 16:38:06 +01003905 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003906 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003907 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003908 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003909 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3910 onUserAdded(userId);
3911 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3912 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003913 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3914 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003915 }
3916 }
3917 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003918
Robin Lee95204e02017-01-27 11:59:22 +00003919 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3920 @Override
3921 public void onReceive(Context context, Intent intent) {
3922 // Try creating lockdown tracker, since user present usually means
3923 // unlocked keystore.
3924 updateLockdownVpn();
3925 mContext.unregisterReceiver(this);
3926 }
3927 };
3928
Robert Greenwalta67be032014-05-16 15:49:14 -07003929 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3930 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003931 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3932 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003933
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003934 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3935 // Map from UID to number of NetworkRequests that UID has filed.
3936 @GuardedBy("mUidToNetworkRequestCount")
3937 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3938
Robert Greenwalta67be032014-05-16 15:49:14 -07003939 private static class NetworkFactoryInfo {
3940 public final String name;
3941 public final Messenger messenger;
3942 public final AsyncChannel asyncChannel;
3943
3944 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3945 this.name = name;
3946 this.messenger = messenger;
3947 this.asyncChannel = asyncChannel;
3948 }
3949 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003950
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003951 private void ensureNetworkRequestHasType(NetworkRequest request) {
3952 if (request.type == NetworkRequest.Type.NONE) {
3953 throw new IllegalArgumentException(
3954 "All NetworkRequests in ConnectivityService must have a type");
3955 }
3956 }
3957
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003958 /**
3959 * Tracks info about the requester.
3960 * Also used to notice when the calling process dies so we can self-expire
3961 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003962 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003964 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003965 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003966 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003967 final int mPid;
3968 final int mUid;
3969 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003971 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003972 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003973 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 mPendingIntent = pi;
3975 messenger = null;
3976 mBinder = null;
3977 mPid = getCallingPid();
3978 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003979 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003980 }
3981
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003982 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 super();
3984 messenger = m;
3985 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003986 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987 mBinder = binder;
3988 mPid = getCallingPid();
3989 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003990 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003991 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003992
3993 try {
3994 mBinder.linkToDeath(this, 0);
3995 } catch (RemoteException e) {
3996 binderDied();
3997 }
3998 }
3999
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004000 private void enforceRequestCountLimit() {
4001 synchronized (mUidToNetworkRequestCount) {
4002 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4003 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004004 throw new ServiceSpecificException(
4005 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004006 }
4007 mUidToNetworkRequestCount.put(mUid, networkRequests);
4008 }
4009 }
4010
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 if (mBinder != null) {
4013 mBinder.unlinkToDeath(this, 0);
4014 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004015 }
4016
4017 public void binderDied() {
4018 log("ConnectivityService NetworkRequestInfo binderDied(" +
4019 request + ", " + mBinder + ")");
4020 releaseNetworkRequest(request);
4021 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004022
4023 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004024 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004025 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004026 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 }
4028
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004029 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4030 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4031 if (badCapability != null) {
4032 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004033 }
4034 }
4035
Erik Kline9d598e12015-07-13 16:37:51 +09004036 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004037 final SortedSet<Integer> thresholds = new TreeSet();
4038 synchronized (nai) {
4039 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4040 if (nri.request.networkCapabilities.hasSignalStrength() &&
4041 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4042 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4043 }
4044 }
4045 }
Erik Kline9d598e12015-07-13 16:37:51 +09004046 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004047 }
4048
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004049 private void updateSignalStrengthThresholds(
4050 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4051 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004052 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004053 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4054
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004055 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004056 String detail;
4057 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4058 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4059 } else {
4060 detail = reason;
4061 }
4062 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4063 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4064 }
4065
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004066 nai.asyncChannel.sendMessage(
4067 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004068 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004069 }
4070
Etan Cohen859748f2017-04-03 17:42:34 -07004071 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4072 if (nc == null) {
4073 return;
4074 }
4075 NetworkSpecifier ns = nc.getNetworkSpecifier();
4076 if (ns == null) {
4077 return;
4078 }
4079 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4080 ns.assertValidFromUid(Binder.getCallingUid());
4081 }
4082
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 @Override
4084 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004085 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004086 final NetworkRequest.Type type = (networkCapabilities == null)
4087 ? NetworkRequest.Type.TRACK_DEFAULT
4088 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004089 // If the requested networkCapabilities is null, take them instead from
4090 // the default network request. This allows callers to keep track of
4091 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004092 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004093 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4094 enforceAccessPermission();
4095 } else {
4096 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4097 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004098 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4099 // of the app when the request is filed, but we never change the request if the app
4100 // changes network state. http://b/29964605
4101 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004102 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004103 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004104
Etan Cohenba07c8c2017-02-05 10:42:27 -08004105 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 throw new IllegalArgumentException("Bad timeout specified");
4107 }
Etan Cohen859748f2017-04-03 17:42:34 -07004108 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004109
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004110 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004111 nextNetworkRequestId(), type);
4112 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004113 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004114
4115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004116 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004118 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119 }
4120 return networkRequest;
4121 }
4122
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004123 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004124 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004125 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126 } else {
4127 enforceChangePermission();
4128 }
4129 }
4130
fenglub15e72b2015-03-20 11:29:56 -07004131 @Override
fengludb571472015-04-21 17:12:05 -07004132 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004133 enforceAccessPermission();
4134 NetworkAgentInfo nai = null;
4135 if (network == null) {
4136 return false;
4137 }
4138 synchronized (mNetworkForNetId) {
4139 nai = mNetworkForNetId.get(network.netId);
4140 }
4141 if (nai != null) {
4142 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4143 return true;
4144 }
4145 return false;
4146 }
4147
Felipe Lemeee27cab2016-06-20 16:36:29 -07004148 private boolean isSystem(int uid) {
4149 return uid < Process.FIRST_APPLICATION_UID;
4150 }
fenglub15e72b2015-03-20 11:29:56 -07004151
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004152 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004153 final int uid = Binder.getCallingUid();
4154 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004155 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004156 return;
4157 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004158 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4159 // Policy already enforced.
4160 return;
4161 }
4162 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4163 // If UID is restricted, don't allow them to bring up metered APNs.
4164 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004165 }
4166 }
4167
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 @Override
4169 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4170 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 checkNotNull(operation, "PendingIntent cannot be null.");
4172 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4173 enforceNetworkRequestPermissions(networkCapabilities);
4174 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004175 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004176 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004177
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004179 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4180 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004181 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004182 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4183 nri));
4184 return networkRequest;
4185 }
4186
Jeremy Joslin79294842014-12-03 17:15:28 -08004187 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4188 mHandler.sendMessageDelayed(
4189 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4190 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4191 }
4192
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 @Override
4194 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004195 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4197 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 }
4199
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004200 // In order to implement the compatibility measure for pre-M apps that call
4201 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4202 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4203 // This ensures it has permission to do so.
4204 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4205 if (nc == null) {
4206 return false;
4207 }
4208 int[] transportTypes = nc.getTransportTypes();
4209 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4210 return false;
4211 }
4212 try {
4213 mContext.enforceCallingOrSelfPermission(
4214 android.Manifest.permission.ACCESS_WIFI_STATE,
4215 "ConnectivityService");
4216 } catch (SecurityException e) {
4217 return false;
4218 }
4219 return true;
4220 }
4221
Robert Greenwalt9258c642014-03-26 16:47:06 -07004222 @Override
4223 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4224 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004225 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4226 enforceAccessPermission();
4227 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004228
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004229 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4230 if (!ConnectivityManager.checkChangePermission(mContext)) {
4231 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4232 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4233 // onLost and onAvailable callbacks when networks move in and out of the background.
4234 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4235 // can't request networks.
4236 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4237 }
Etan Cohen859748f2017-04-03 17:42:34 -07004238 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004239
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004240 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004241 NetworkRequest.Type.LISTEN);
4242 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004243 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004244
4245 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4246 return networkRequest;
4247 }
4248
4249 @Override
4250 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4251 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004252 checkNotNull(operation, "PendingIntent cannot be null.");
4253 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4254 enforceAccessPermission();
4255 }
Etan Cohen859748f2017-04-03 17:42:34 -07004256 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004257
Erik Kline7523eb32015-07-09 18:24:03 +09004258 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004259 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4260 NetworkRequest.Type.LISTEN);
4261 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004262 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004263
4264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004265 }
4266
Erik Klineacdd6392016-07-07 16:50:58 +09004267 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004268 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004269 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004270 mHandler.sendMessage(mHandler.obtainMessage(
4271 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004272 }
4273
4274 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004275 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004276 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004277 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4278 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004279 }
4280
Robert Greenwalta67be032014-05-16 15:49:14 -07004281 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004282 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004283 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4284 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4285 }
4286
4287 @Override
4288 public void unregisterNetworkFactory(Messenger messenger) {
4289 enforceConnectivityInternalPermission();
4290 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4291 }
4292
4293 private void handleUnregisterNetworkFactory(Messenger messenger) {
4294 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4295 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004296 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004297 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004299 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004300 }
4301
Robert Greenwalt7b816022014-04-18 15:25:25 -07004302 /**
4303 * NetworkAgentInfo supporting a request by requestId.
4304 * These have already been vetted (their Capabilities satisfy the request)
4305 * and the are the highest scored network available.
4306 * the are keyed off the Requests requestId.
4307 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004308 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004309 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4310 new SparseArray<NetworkAgentInfo>();
4311
Paul Jensen31a94f42015-02-13 14:18:39 -05004312 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4313 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4315 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004316 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4317 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4318 // there may not be a strict 1:1 correlation between the two.
4319 @GuardedBy("mNetworkForNetId")
4320 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321
Robert Greenwalt7b816022014-04-18 15:25:25 -07004322 // NetworkAgentInfo keyed off its connecting messenger
4323 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004324 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004325 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4326 new HashMap<Messenger, NetworkAgentInfo>();
4327
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004328 @GuardedBy("mBlockedAppUids")
4329 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4330
Paul Jensen2c311d62014-11-17 12:34:51 -05004331 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332 private final NetworkRequest mDefaultRequest;
4333
Erik Klineda4bfa82015-04-30 12:58:40 +09004334 // Request used to optionally keep mobile data active even when higher
4335 // priority networks like Wi-Fi are active.
4336 private final NetworkRequest mDefaultMobileDataRequest;
4337
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004338 private NetworkAgentInfo getDefaultNetwork() {
4339 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4340 }
4341
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004342 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004343 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004344 }
4345
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004346 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4347 return nri.request.requestId == mDefaultRequest.requestId;
4348 }
4349
Paul Jensen31a94f42015-02-13 14:18:39 -05004350 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004351 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004352 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004353 enforceConnectivityInternalPermission();
4354
Paul Jensen2c311d62014-11-17 12:34:51 -05004355 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4356 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004357 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004358 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4359 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004360 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004361 synchronized (this) {
4362 nai.networkMonitor.systemReady = mSystemReady;
4363 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004364 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4365 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004366 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004368 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004369 }
4370
4371 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4372 if (VDBG) log("Got NetworkAgent Messenger");
4373 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004374 synchronized (mNetworkForNetId) {
4375 mNetworkForNetId.put(na.network.netId, na);
4376 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004377 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4378 NetworkInfo networkInfo = na.networkInfo;
4379 na.networkInfo = null;
4380 updateNetworkInfo(na, networkInfo);
4381 }
4382
4383 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4384 LinkProperties newLp = networkAgent.linkProperties;
4385 int netId = networkAgent.network.netId;
4386
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004387 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4388 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004389 if (networkAgent.clatd != null) {
4390 networkAgent.clatd.fixupLinkProperties(oldLp);
4391 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004392
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004393 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 updateMtu(newLp, oldLp);
4395 // TODO - figure out what to do for clat
4396// for (LinkProperties lp : newLp.getStackedLinks()) {
4397// updateMtu(lp, null);
4398// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004399 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004400
Erik Kline94887872016-04-05 13:30:49 +09004401 updateRoutes(newLp, oldLp, netId);
4402 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004403
Hugo Benichi6f62b732017-06-27 15:13:20 +09004404 // Start or stop clat accordingly to network state.
Hugo Benichi37119102017-08-31 14:32:54 +00004405 updateClat(networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004406 if (isDefaultNetwork(networkAgent)) {
4407 handleApplyDefaultProxy(newLp.getHttpProxy());
4408 } else {
4409 updateProxy(newLp, oldLp, networkAgent);
4410 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004411 // TODO - move this check to cover the whole function
4412 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004413 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004414 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4415 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004416
4417 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004418 }
4419
Hugo Benichi37119102017-08-31 14:32:54 +00004420 private void updateClat(NetworkAgentInfo nai) {
4421 if (Nat464Xlat.requiresClat(nai)) {
4422 maybeStartClat(nai);
4423 } else {
4424 maybeStopClat(nai);
4425 }
4426 }
4427
4428 /** Ensure clat has started for this network. */
4429 private void maybeStartClat(NetworkAgentInfo nai) {
4430 if (nai.clatd != null && nai.clatd.isStarted()) {
4431 return;
4432 }
4433 nai.clatd = new Nat464Xlat(mNetd, mTrackerHandler, nai);
4434 nai.clatd.start();
4435 }
4436
4437 /** Ensure clat has stopped for this network. */
4438 private void maybeStopClat(NetworkAgentInfo nai) {
4439 if (nai.clatd == null) {
4440 return;
4441 }
4442 nai.clatd.stop();
4443 nai.clatd = null;
4444 }
4445
Joel Scherpelz668370b2017-06-08 15:35:21 +09004446 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004447 // Marks are only available on WiFi interaces. Checking for
4448 // marks on unsupported interfaces is harmless.
4449 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4450 return;
4451 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004452
Joel Scherpelz668370b2017-06-08 15:35:21 +09004453 int mark = mContext.getResources().getInteger(
4454 com.android.internal.R.integer.config_networkWakeupPacketMark);
4455 int mask = mContext.getResources().getInteger(
4456 com.android.internal.R.integer.config_networkWakeupPacketMask);
4457
4458 // Mask/mark of zero will not detect anything interesting.
4459 // Don't install rules unless both values are nonzero.
4460 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004461 return;
4462 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004463
4464 final String prefix = "iface:" + iface;
4465 try {
4466 if (add) {
4467 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4468 } else {
4469 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4470 }
4471 } catch (Exception e) {
4472 loge("Exception modifying wakeup packet monitoring: " + e);
4473 }
4474
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004475 }
4476
4477 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4478 NetworkCapabilities caps) {
Paul Jensen992f2522014-04-28 10:33:11 -04004479 CompareResult<String> interfaceDiff = new CompareResult<String>();
4480 if (oldLp != null) {
4481 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4482 } else if (newLp != null) {
4483 interfaceDiff.added = newLp.getAllInterfaceNames();
4484 }
4485 for (String iface : interfaceDiff.added) {
4486 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004487 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004488 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004489 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004490 } catch (Exception e) {
4491 loge("Exception adding interface: " + e);
4492 }
4493 }
4494 for (String iface : interfaceDiff.removed) {
4495 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004496 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004497 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004498 mNetd.removeInterfaceFromNetwork(iface, netId);
4499 } catch (Exception e) {
4500 loge("Exception removing interface: " + e);
4501 }
4502 }
4503 }
4504
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004505 /**
4506 * Have netd update routes from oldLp to newLp.
4507 * @return true if routes changed between oldLp and newLp
4508 */
4509 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4511 if (oldLp != null) {
4512 routeDiff = oldLp.compareAllRoutes(newLp);
4513 } else if (newLp != null) {
4514 routeDiff.added = newLp.getAllRoutes();
4515 }
4516
4517 // add routes before removing old in case it helps with continuous connectivity
4518
4519 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4520 for (RouteInfo route : routeDiff.added) {
4521 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004522 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004523 try {
4524 mNetd.addRoute(netId, route);
4525 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004526 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4527 loge("Exception in addRoute for non-gateway: " + e);
4528 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004529 }
4530 }
4531 for (RouteInfo route : routeDiff.added) {
4532 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004533 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 try {
4535 mNetd.addRoute(netId, route);
4536 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004537 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4538 loge("Exception in addRoute for gateway: " + e);
4539 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 }
4541 }
4542
4543 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004544 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 try {
4546 mNetd.removeRoute(netId, route);
4547 } catch (Exception e) {
4548 loge("Exception in removeRoute: " + e);
4549 }
4550 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004551 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 }
Erik Kline41368502015-06-17 13:19:54 +09004553
Erik Kline94887872016-04-05 13:30:49 +09004554 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4555 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4556 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 }
Erik Kline94887872016-04-05 13:30:49 +09004558
4559 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004560 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004561 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004562 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004563 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4564 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004565 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004566 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004567 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4568 if (defaultNai != null && defaultNai.network.netId == netId) {
4569 setDefaultDnsSystemProperties(dnses);
4570 }
Erik Kline94887872016-04-05 13:30:49 +09004571 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 }
4573
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004574 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4575 int last = 0;
4576 for (InetAddress dns : dnses) {
4577 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004578 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004579 }
4580 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004581 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004582 }
4583 mNumDnsEntries = last;
4584 }
4585
Erik Kline4edba012017-04-07 15:29:29 +09004586 private void setNetDnsProperty(int which, String value) {
4587 final String key = "net.dns" + which;
4588 // Log and forget errors setting unsupported properties.
4589 try {
4590 mSystemProperties.set(key, value);
4591 } catch (Exception e) {
4592 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4593 }
4594 }
4595
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004596 private String getNetworkPermission(NetworkCapabilities nc) {
4597 // TODO: make these permission strings AIDL constants instead.
4598 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4599 return NetworkManagementService.PERMISSION_SYSTEM;
4600 }
4601 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4602 return NetworkManagementService.PERMISSION_NETWORK;
4603 }
4604 return null;
4605 }
4606
Paul Jensen3d194ea2015-06-16 14:27:36 -04004607 /**
4608 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4609 * augmented with any stateful capabilities implied from {@code networkAgent}
4610 * (e.g., validated status and captive portal status).
4611 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004612 * @param oldScore score of the network before any of the changes that prompted us
4613 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004614 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004615 * @param networkCapabilities the new network capabilities.
4616 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004617 private void updateCapabilities(
4618 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004619 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichi80e8e0f2017-08-18 14:41:22 +09004620 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4621 networkCapabilities)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004622 // TODO: consider not complaining when a network agent degrade its capabilities if this
4623 // does not cause any request (that is not a listen) currently matching that agent to
4624 // stop being matched by the updated agent.
Hugo Benichi683ea482017-07-25 11:40:56 +09004625 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4626 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004627 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004628 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004629 }
4630
Paul Jensen3d194ea2015-06-16 14:27:36 -04004631 // Don't modify caller's NetworkCapabilities.
4632 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004633 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004634 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4635 } else {
4636 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4637 }
Paul Jensene0988542015-06-25 15:30:08 -04004638 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004639 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4640 } else {
4641 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4642 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004643 if (nai.isBackgroundNetwork()) {
4644 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4645 } else {
4646 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4647 }
4648
4649 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4650
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004651 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4652 final String newPermission = getNetworkPermission(networkCapabilities);
4653 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004654 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004655 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004656 } catch (RemoteException e) {
4657 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004658 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004659 }
4660
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004661 final NetworkCapabilities prevNc = nai.networkCapabilities;
4662 synchronized (nai) {
4663 nai.networkCapabilities = networkCapabilities;
4664 }
4665 if (nai.getCurrentScore() == oldScore &&
4666 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4667 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4668 // the change we're processing can't affect any requests, it can only affect the listens
4669 // on this network. We might have been called by rematchNetworkAndRequests when a
4670 // network changed foreground state.
4671 processListenRequests(nai, true);
4672 } else {
4673 // If the requestable capabilities have changed or the score changed, we can't have been
4674 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004675 rematchAllNetworksAndRequests(nai, oldScore);
4676 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004677 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 }
4679
Paul Jensenc8b9a742014-09-30 15:37:41 -04004680 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004681 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4682 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004683 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004684 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004685 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4686 }
4687 }
4688
Robert Greenwalt7b816022014-04-18 15:25:25 -07004689 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4690 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004691 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004692 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4693 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
4695 }
4696
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004697 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4698 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004699 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004700 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004701 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4702 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004703 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004704 sendIntent(nri.mPendingIntent, intent);
4705 }
4706 // else not handled
4707 }
4708
4709 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4710 mPendingIntentWakeLock.acquire();
4711 try {
4712 if (DBG) log("Sending " + pendingIntent);
4713 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4714 } catch (PendingIntent.CanceledException e) {
4715 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4716 mPendingIntentWakeLock.release();
4717 releasePendingNetworkRequest(pendingIntent);
4718 }
4719 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4720 }
4721
4722 @Override
4723 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4724 String resultData, Bundle resultExtras) {
4725 if (DBG) log("Finished sending " + pendingIntent);
4726 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004727 // Release with a delay so the receiving client has an opportunity to put in its
4728 // own request.
4729 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004730 }
4731
Hugo Benichidba33db2017-03-23 22:40:44 +09004732 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004733 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004734 if (nri.messenger == null) {
4735 return; // Default request has no msgr
4736 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004737 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004738 // TODO: check if defensive copies of data is needed.
4739 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004740 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004741 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4742 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004743 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004744 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004745 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004746 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004747 break;
4748 }
4749 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004750 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004751 break;
4752 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004753 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004754 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755 break;
4756 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004757 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004758 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004759 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004761 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004762 String notification = ConnectivityManager.getCallbackName(notificationType);
4763 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004764 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004765 nri.messenger.send(msg);
4766 } catch (RemoteException e) {
4767 // may occur naturally in the race of binder death.
4768 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4769 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 }
4771
Hugo Benichidba33db2017-03-23 22:40:44 +09004772 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4773 bundle.putParcelable(t.getClass().getSimpleName(), t);
4774 }
4775
Paul Jensenc8b9a742014-09-30 15:37:41 -04004776 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004777 if (nai.numRequestNetworkRequests() != 0) {
4778 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4779 NetworkRequest nr = nai.requestAt(i);
4780 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004781 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004782 loge("Dead network still had at least " + nr);
4783 break;
4784 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004785 }
4786 nai.asyncChannel.disconnect();
4787 }
4788
Robert Greenwalt7b816022014-04-18 15:25:25 -07004789 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4790 if (oldNetwork == null) {
4791 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4792 return;
4793 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004794 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004795
4796 // If we get here it means that the last linger timeout for this network expired. So there
4797 // must be no other active linger timers, and we must stop lingering.
4798 oldNetwork.clearLingerState();
4799
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004800 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004801 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004802 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004803 } else {
4804 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004805 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4806 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004807 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004808 }
4809
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004810 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004811 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004812 setupDataActivityTracking(newNetwork);
4813 try {
4814 mNetd.setDefaultNetId(newNetwork.network.netId);
4815 } catch (Exception e) {
4816 loge("Exception setting default network :" + e);
4817 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004818 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004819 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004820 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004821 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004822 }
4823
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004824 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004825 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4826 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4827 NetworkRequest nr = nri.request;
4828 if (!nr.isListen()) continue;
4829 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4830 nai.removeRequest(nri.request.requestId);
4831 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4832 }
4833 }
4834
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004835 if (capabilitiesChanged) {
4836 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4837 }
4838
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004839 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4840 NetworkRequest nr = nri.request;
4841 if (!nr.isListen()) continue;
4842 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4843 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004844 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004845 }
4846 }
4847 }
4848
Paul Jensen2161a8e2014-09-11 11:00:39 -04004849 // Handles a network appearing or improving its score.
4850 //
4851 // - Evaluates all current NetworkRequests that can be
4852 // satisfied by newNetwork, and reassigns to newNetwork
4853 // any such requests for which newNetwork is the best.
4854 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004855 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004856 // needed. A network is needed if it is the best network for
4857 // one or more NetworkRequests, or if it is a VPN.
4858 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004859 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004860 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004861 //
4862 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4863 // networks that have no chance (i.e. even if validated)
4864 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004865 //
4866 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4867 // it does not remove NetworkRequests that other Networks could better satisfy.
4868 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4869 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4870 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004871 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004872 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004873 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4874 // performed to tear down unvalidated networks that have no chance (i.e. even if
4875 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004876 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004877 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004878 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004879 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004881 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882
4883 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4884 final int score = newNetwork.getCurrentScore();
4885
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004886 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004887
Paul Jensen2161a8e2014-09-11 11:00:39 -04004888 // Find and migrate to this Network any NetworkRequests for
4889 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004890 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004891 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004892 NetworkCapabilities nc = newNetwork.networkCapabilities;
4893 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004894 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004895 // Process requests in the first pass and listens in the second pass. This allows us to
4896 // change a network's capabilities depending on which requests it has. This is only
4897 // correct if the change in capabilities doesn't affect whether the network satisfies
4898 // requests or not, and doesn't affect the network's score.
4899 if (nri.request.isListen()) continue;
4900
Paul Jensencf4c2c62015-07-01 14:16:32 -04004901 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4902 final boolean satisfies = newNetwork.satisfies(nri.request);
4903 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004904 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004905 log("Network " + newNetwork.name() + " was already satisfying" +
4906 " request " + nri.request.requestId + ". No change.");
4907 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004908 keep = true;
4909 continue;
4910 }
4911
4912 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004913 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004914 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004915 // next check if it's better than any current network we're using for
4916 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 if (VDBG) {
4918 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004919 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004920 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004922 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004923 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004924 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004925 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004926 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004927 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928 affectedNetworks.add(currentNetwork);
4929 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004930 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004932 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004933 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004934 if (!newNetwork.addRequest(nri.request)) {
4935 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4936 }
4937 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004939 // Tell NetworkFactories about the new score, so they can stop
4940 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 // TODO - this could get expensive if we have alot of requests for this
4942 // network. Think about if there is a way to reduce this. Push
4943 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004944 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004945 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004946 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004947 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004948 if (currentNetwork != null) {
4949 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4950 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004951 }
4952 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004953 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4955 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004956 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004957 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4958 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4959 // This means this code doesn't have to handle the case where "currentNetwork" no
4960 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4961 if (DBG) {
4962 log("Network " + newNetwork.name() + " stopped satisfying" +
4963 " request " + nri.request.requestId);
4964 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004965 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004966 if (currentNetwork == newNetwork) {
4967 mNetworkForRequestId.remove(nri.request.requestId);
4968 sendUpdatedScoreToFactories(nri.request, 0);
4969 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004970 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4971 newNetwork.name() +
4972 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004974 // TODO: Technically, sending CALLBACK_LOST here is
4975 // incorrect if there is a replacement network currently
4976 // connected that can satisfy nri, which is a request
4977 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004978 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4979 // so this code is only incorrect for a network that loses
4980 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004981 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004982 }
4983 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004984 if (isNewDefault) {
4985 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004986 makeDefault(newNetwork);
4987 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4988 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004989 // Have a new default network, release the transition wakelock in
4990 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004991 }
4992
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004993 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4994 Slog.wtf(TAG, String.format(
4995 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07004996 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004997 }
4998 if (newNetwork.getCurrentScore() != score) {
4999 Slog.wtf(TAG, String.format(
5000 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005001 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005002 }
5003
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005004 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005005 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5006 // If the network went from background to foreground or vice versa, we need to update
5007 // its foreground state. It is safe to do this after rematching the requests because
5008 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5009 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005010 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005011 } else {
5012 processListenRequests(newNetwork, false);
5013 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005014
Paul Jensencf4c2c62015-07-01 14:16:32 -04005015 // do this after the default net is switched, but
5016 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005017 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005018
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005019 // Linger any networks that are no longer needed. This should be done after sending the
5020 // available callback for newNetwork.
5021 for (NetworkAgentInfo nai : affectedNetworks) {
5022 updateLingerState(nai, now);
5023 }
5024 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5025 // does not need to be done in any particular order.
5026 updateLingerState(newNetwork, now);
5027
Paul Jensencf4c2c62015-07-01 14:16:32 -04005028 if (isNewDefault) {
5029 // Maintain the illusion: since the legacy API only
5030 // understands one network at a time, we must pretend
5031 // that the current default network disconnected before
5032 // the new one connected.
5033 if (oldDefaultNetwork != null) {
5034 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5035 oldDefaultNetwork, true);
5036 }
5037 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5038 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5039 notifyLockdownVpn(newNetwork);
5040 }
5041
Robert Greenwalt7b816022014-04-18 15:25:25 -07005042 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005043 // Notify battery stats service about this network, both the normal
5044 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005045 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005046 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005047 final IBatteryStats bs = BatteryStatsService.getService();
5048 final int type = newNetwork.networkInfo.getType();
5049
5050 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5051 bs.noteNetworkInterfaceType(baseIface, type);
5052 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5053 final String stackedIface = stacked.getInterfaceName();
5054 bs.noteNetworkInterfaceType(stackedIface, type);
5055 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5056 }
5057 } catch (RemoteException ignored) {
5058 }
5059
Robert Greenwalt152ed372014-12-17 17:19:53 -08005060 // This has to happen after the notifyNetworkCallbacks as that tickles each
5061 // ConnectivityManager instance so that legacy requests correctly bind dns
5062 // requests to this network. The legacy users are listening for this bcast
5063 // and will generally do a dns request so they can ensureRouteToHost and if
5064 // they do that before the callbacks happen they'll use the default network.
5065 //
5066 // TODO: Is there still a race here? We send the broadcast
5067 // after sending the callback, but if the app can receive the
5068 // broadcast before the callback, it might still break.
5069 //
5070 // This *does* introduce a race where if the user uses the new api
5071 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5072 // they may get old info. Reverse this after the old startUsing api is removed.
5073 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005074 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5075 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005076 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005077 // legacy type tracker filters out repeat adds
5078 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5079 }
5080 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005081
5082 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5083 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5084 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5085 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5086 if (newNetwork.isVPN()) {
5087 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5088 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005089 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005090 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5091 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005092 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005093 if (nai.getLingerExpiry() > 0) {
5094 // This network has active linger timers and no requests, but is not
5095 // lingering. Linger it.
5096 //
5097 // One way (the only way?) this can happen if this network is unvalidated
5098 // and became unneeded due to another network improving its score to the
5099 // point where this network will no longer be able to satisfy any requests
5100 // even if it validates.
5101 updateLingerState(nai, now);
5102 } else {
5103 if (DBG) log("Reaping " + nai.name());
5104 teardownUnneededNetwork(nai);
5105 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005106 }
5107 }
5108 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005109 }
5110
Paul Jensen1c7ba022015-06-16 14:27:36 -04005111 /**
5112 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5113 * being disconnected.
5114 * @param changed If only one Network's score or capabilities have been modified since the last
5115 * time this function was called, pass this Network in this argument, otherwise pass
5116 * null.
5117 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5118 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5119 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5120 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5121 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005122 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005123 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005124 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5125 // to avoid the slowness. It is not simply enough to process just "changed", for
5126 // example in the case where "changed"'s score decreases and another network should begin
5127 // satifying a NetworkRequest that "changed" currently satisfies.
5128
5129 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5130 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5131 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005132 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005133 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005134 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005135 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005136 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5137 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5138 // Rematch higher scoring networks first to prevent requests first matching a lower
5139 // scoring network and then a higher scoring network, which could produce multiple
5140 // callbacks and inadvertently unlinger networks.
5141 Arrays.sort(nais);
5142 for (NetworkAgentInfo nai : nais) {
5143 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005144 // Only reap the last time through the loop. Reaping before all rematching
5145 // is complete could incorrectly teardown a network that hasn't yet been
5146 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005147 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005148 : ReapUnvalidatedNetworks.REAP,
5149 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005150 }
5151 }
5152 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005153
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005154 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005155 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005156 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005157 // For now only update icons for default connection.
5158 // TODO: Update WiFi and cellular icons separately. b/17237507
5159 if (!isDefaultNetwork(nai)) return;
5160
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005161 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005162 // Don't repeat publish.
5163 if (newInetCondition == mDefaultInetConditionPublished) return;
5164
5165 mDefaultInetConditionPublished = newInetCondition;
5166 sendInetConditionBroadcast(nai.networkInfo);
5167 }
5168
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005169 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5170 if (mLockdownTracker != null) {
5171 if (nai != null && nai.isVPN()) {
5172 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5173 } else {
5174 mLockdownTracker.onNetworkInfoChanged();
5175 }
5176 }
5177 }
5178
Robert Greenwalt7b816022014-04-18 15:25:25 -07005179 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005180 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005181 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005182 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005183 synchronized (networkAgent) {
5184 oldInfo = networkAgent.networkInfo;
5185 networkAgent.networkInfo = newInfo;
5186 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005187 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005188
5189 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005190 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5191 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5192 notifyIfacesChangedForNetworkStats();
5193 } else if (VDBG) log("ignoring duplicate network state non-change");
5194 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005195 return;
5196 }
5197 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 Saini0e94c362017-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
Hugo Benichicfddd682016-05-31 16:28:06 +09005542 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005543 int newNetid = NETID_UNSET;
5544 int prevNetid = NETID_UNSET;
5545 int[] transports = new int[0];
5546 boolean hadIPv4 = false;
5547 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005548
Hugo Benichi5f16f762016-04-20 12:09:33 +09005549 if (newNai != null) {
5550 newNetid = newNai.network.netId;
5551 transports = newNai.networkCapabilities.getTransportTypes();
5552 }
5553 if (prevNai != null) {
5554 prevNetid = prevNai.network.netId;
5555 final LinkProperties lp = prevNai.linkProperties;
5556 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5557 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5558 }
5559
Hugo Benichicfddd682016-05-31 16:28:06 +09005560 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5561 }
5562
5563 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5564 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005565 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005566
5567 private static boolean toBool(int encodedBoolean) {
5568 return encodedBoolean != 0; // Only 0 means false.
5569 }
5570
5571 private static int encodeBool(boolean b) {
5572 return b ? 1 : 0;
5573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574}