blob: a2293a777afcb3d09d08bd13650ef877b44e9b82 [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;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Etan Cohena7434272017-04-03 12:17:51 -070065import android.net.MatchAllNetworkSpecifier;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070066import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070068import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070069import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070072import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070073import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070074import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040075import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070076import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040077import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040078import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090079import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090080import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090081import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090082import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080084import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070085import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040086import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070088import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070090import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Looper;
92import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070093import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070094import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070095import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070096import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080098import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090099import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500114import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400120import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700122import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700124import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800125import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700126import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700127import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700128import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900129import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900130import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700131import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400133import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900134import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700135import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900136import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900137import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700138import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600139import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900141import com.android.server.connectivity.NetworkNotificationManager;
142import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400143import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700144import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800145import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700146import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700147import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700148import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600149
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700150import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700151
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import org.xmlpull.v1.XmlPullParser;
153import org.xmlpull.v1.XmlPullParserException;
154
155import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700157import java.io.FileNotFoundException;
158import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700159import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700161import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.net.InetAddress;
163import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700164import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700167import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700169import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700170import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700171import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700172import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600173import java.util.SortedSet;
174import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
176/**
177 * @hide
178 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800179public class ConnectivityService extends IConnectivityManager.Stub
180 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900181 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
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
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700225 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
226 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700227 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600228 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700229 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700230 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600231 @GuardedBy("mRulesLock")
232 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
233 /** Flag indicating if background data is restricted. */
234 @GuardedBy("mRulesLock")
235 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700236
Erik Klineda4bfa82015-04-30 12:58:40 +0900237 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700239 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700240 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800242 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700245 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700247 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800248 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700249 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700250
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700251 private String mCurrentTcpBufferSizes;
252
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700253 private static final int ENABLED = 1;
254 private static final int DISABLED = 0;
255
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900256 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900257 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
258 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900259
Paul Jensenb10e37f2014-11-25 12:33:08 -0500260 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400261 // Tear down networks that have no chance (e.g. even if validated) of becoming
262 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 // all networks have been rematched against all NetworkRequests.
264 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400265 // Don't reap networks. This should be passed when some networks have not yet been
266 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500267 DONT_REAP
268 };
269
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900270 private enum UnneededFor {
271 LINGER, // Determine whether this network is unneeded and should be lingered.
272 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
273 }
274
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700276 * used internally to change our mobile data enabled flag
277 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700278 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700279
280 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700281 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700282 * from one net to another. Clear happens when we get a new
283 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
284 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700286 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700287
Robert Greenwalt434203a2010-10-11 16:00:27 -0700288 /**
289 * used internally to reload global proxy settings
290 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700291 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700292
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700293 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400294 * PAC manager has received new port.
295 */
296 private static final int EVENT_PROXY_HAS_CHANGED = 16;
297
Robert Greenwalte049c232014-04-11 15:53:27 -0700298 /**
299 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700301 */
302 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
303
Robert Greenwalt7b816022014-04-18 15:25:25 -0700304 /**
305 * used internally when registering NetworkAgents
306 * obj = Messenger
307 */
308 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
309
Robert Greenwalt9258c642014-03-26 16:47:06 -0700310 /**
311 * used to add a network request
312 * includes a NetworkRequestInfo
313 */
314 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
315
316 /**
317 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900318 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700319 * cancel it.
320 * includes a NetworkRequestInfo
321 */
322 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
323
324 /**
325 * used to add a network listener - no request
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
329
330 /**
331 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400332 * arg1 = UID of caller
333 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
336
Robert Greenwalta67be032014-05-16 15:49:14 -0700337 /**
338 * used internally when registering NetworkFactories
339 * obj = Messenger
340 */
341 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
342
Robert Greenwalt27711812014-06-25 16:45:57 -0700343 /**
344 * used internally to expire a wakelock when transitioning
345 * from one net to another. Expire happens when we fail to find
346 * a new network (typically after 1 minute) -
347 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
348 * a replacement network.
349 */
350 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
351
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700352 /**
353 * Used internally to indicate the system is ready.
354 */
355 private static final int EVENT_SYSTEM_READY = 25;
356
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800357 /**
358 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400359 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800360 */
361 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
362
363 /**
364 * used to remove a pending intent and its associated network request.
365 * arg1 = UID of caller
366 * obj = PendingIntent
367 */
368 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
369
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900370 /**
371 * used to specify whether a network should be used even if unvalidated.
372 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
373 * arg2 = whether to remember this choice in the future (1 or 0)
374 * obj = network
375 */
376 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
377
378 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900379 * used to specify whether a network should not be penalized when it becomes unvalidated.
380 */
381 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
382
383 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900384 * used to ask the user to confirm a connection to an unvalidated network.
385 * obj = network
386 */
387 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700388
Erik Klineda4bfa82015-04-30 12:58:40 +0900389 /**
390 * used internally to (re)configure mobile data always-on settings.
391 */
392 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
393
Paul Jensen694f2b82015-06-17 14:15:39 -0400394 /**
395 * used to add a network listener with a pending intent
396 * obj = NetworkRequestInfo
397 */
398 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
399
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900400 private static String eventName(int what) {
401 return sMagicDecoderRing.get(what, Integer.toString(what));
402 }
403
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900404 /** Handler thread used for both of the handlers below. */
405 @VisibleForTesting
406 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700407 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700408 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700409 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700410 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411
Mike Lockwood0f79b542009-08-14 14:18:49 -0400412 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800413 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400414
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800417 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700418
Robert Greenwalt434203a2010-10-11 16:00:27 -0700419 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400420 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700421 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700422 private boolean mDefaultProxyDisabled = false;
423
Robert Greenwalt434203a2010-10-11 16:00:27 -0700424 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400425 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426
Jason Monk602b2322013-07-03 17:04:33 -0400427 private PacManager mPacManager = null;
428
Erik Klineda4bfa82015-04-30 12:58:40 +0900429 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700430
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400431 private UserManager mUserManager;
432
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700433 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700435
Robert Greenwalt50393202011-06-21 17:26:14 -0700436 // the set of network types that can only be enabled by system/sig apps
437 List mProtectedNetworks;
438
John Spurlockbf991a82013-06-24 14:20:23 -0400439 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700440
Wink Savilleab9321d2013-06-29 21:10:57 -0700441 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400442
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900443 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900444 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900445 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900446
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700447 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
448 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700449 private final static int MAX_NET_ID = 65535;
450 private int mNextNetId = MIN_NET_ID;
451
Robert Greenwalt34524f02014-05-18 16:22:10 -0700452 // sequence number of NetworkRequests
453 private int mNextNetworkRequestId = 1;
454
Erik Kline7523eb32015-07-09 18:24:03 +0900455 // NetworkRequest activity String log entries.
456 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
457 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
458
Hugo Benichic2ae2872016-07-11 11:05:12 +0900459 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900460 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900461 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
462
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900463 private static final int MAX_WAKELOCK_LOGS = 20;
464 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
465
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700466 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
467 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 private static class ValidationLog {
469 final Network mNetwork;
470 final String mNetworkExtraInfo;
471 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700472
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
474 mNetwork = network;
475 mNetworkExtraInfo = networkExtraInfo;
476 mLog = log;
477 }
478 }
479 private final ArrayDeque<ValidationLog> mValidationLogs =
480 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
481
482 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 synchronized(mValidationLogs) {
484 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
485 mValidationLogs.removeLast();
486 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 }
489 }
490
Hugo Benichif9fdf872016-07-28 17:53:06 +0900491 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900492
Erik Kline065ab6e2016-10-02 18:02:14 +0900493 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900494 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900495
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700496 /**
497 * Implements support for the legacy "one network per network type" model.
498 *
499 * We used to have a static array of NetworkStateTrackers, one for each
500 * network type, but that doesn't work any more now that we can have,
501 * for example, more that one wifi network. This class stores all the
502 * NetworkAgentInfo objects that support a given type, but the legacy
503 * API will only see the first one.
504 *
505 * It serves two main purposes:
506 *
507 * 1. Provide information about "the network for a given type" (since this
508 * API only supports one).
509 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
510 * the first network for a given type changes, or if the default network
511 * changes.
512 */
513 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900515 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 /**
519 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
520 * Each list holds references to all NetworkAgentInfos that are used to
521 * satisfy requests for that network type.
522 *
523 * This array is built out at startup such that an unsupported network
524 * doesn't get an ArrayList instance, making this a tristate:
525 * unsupported, supported but not active and active.
526 *
527 * The actual lists are populated when we scan the network types that
528 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900529 *
530 * Threading model:
531 * - addSupportedType() is only called in the constructor
532 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
533 * They are therefore not thread-safe with respect to each other.
534 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
535 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
536 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900538 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700539
540 public LegacyTypeTracker() {
541 mTypeLists = (ArrayList<NetworkAgentInfo>[])
542 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
543 }
544
545 public void addSupportedType(int type) {
546 if (mTypeLists[type] != null) {
547 throw new IllegalStateException(
548 "legacy list for type " + type + "already initialized");
549 }
550 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
551 }
552
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 public boolean isTypeSupported(int type) {
554 return isNetworkTypeValid(type) && mTypeLists[type] != null;
555 }
556
557 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900558 synchronized (mTypeLists) {
559 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
560 return mTypeLists[type].get(0);
561 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
565
Robert Greenwalt8d482522015-06-24 13:23:42 -0700566 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900567 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900571 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 }
573 }
574
575 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 public void add(int type, NetworkAgentInfo nai) {
577 if (!isTypeSupported(type)) {
578 return; // Invalid network type.
579 }
580 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
581
582 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
583 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 return;
585 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900586 synchronized (mTypeLists) {
587 list.add(nai);
588 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900589
590 // 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 +0900591 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900592 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700593 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
594 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
597
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900599 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900600 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
601 if (list == null || list.isEmpty()) {
602 return;
603 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900604 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605
Hugo Benichi78caa2582016-06-21 09:48:07 +0900606 synchronized (mTypeLists) {
607 if (!list.remove(nai)) {
608 return;
609 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610 }
611
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 final DetailedState state = DetailedState.DISCONNECTED;
613
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900614 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(nai, state, type, wasDefault);
616 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 }
618
619 if (!list.isEmpty() && wasFirstNetwork) {
620 if (DBG) log("Other network available for type " + type +
621 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
624 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626 }
627
628 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
630 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900632 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700633 }
634 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700635
Robert Greenwalt8d482522015-06-24 13:23:42 -0700636 // send out another legacy broadcast - currently only used for suspend/unsuspend
637 // toggle
638 public void update(NetworkAgentInfo nai) {
639 final boolean isDefault = isDefaultNetwork(nai);
640 final DetailedState state = nai.networkInfo.getDetailedState();
641 for (int type = 0; type < mTypeLists.length; type++) {
642 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700643 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900644 final boolean isFirst = contains && (nai == list.get(0));
645 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700646 maybeLogBroadcast(nai, state, type, isDefault);
647 sendLegacyNetworkBroadcast(nai, state, type);
648 }
649 }
650 }
651
Lorenzo Colittia793a672014-07-31 23:20:17 +0900652 private String naiToString(NetworkAgentInfo nai) {
653 String name = (nai != null) ? nai.name() : "null";
654 String state = (nai.networkInfo != null) ?
655 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
656 "???/???";
657 return name + " " + state;
658 }
659
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700660 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900661 pw.println("mLegacyTypeTracker:");
662 pw.increaseIndent();
663 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700664 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700666 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900667 pw.println();
668 pw.println("Current state:");
669 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 synchronized (mTypeLists) {
671 for (int type = 0; type < mTypeLists.length; type++) {
672 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
673 for (NetworkAgentInfo nai : mTypeLists[type]) {
674 pw.println(type + " " + naiToString(nai));
675 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900676 }
677 }
678 pw.decreaseIndent();
679 pw.decreaseIndent();
680 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700681 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700682 }
683 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
684
Jeff Sharkey899223b2012-08-04 15:24:58 -0700685 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700686 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900687 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
688 }
689
690 @VisibleForTesting
691 protected ConnectivityService(Context context, INetworkManagementService netManager,
692 INetworkStatsService statsService, INetworkPolicyManager policyManager,
693 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800694 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800695
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900696 mSystemProperties = getSystemProperties();
697
Hugo Benichif9fdf872016-07-28 17:53:06 +0900698 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900699 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900700 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900701 mNetworkRequests.put(mDefaultRequest, defaultNRI);
702 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900703
704 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900705 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700706
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900707 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900708 mHandlerThread.start();
709 mHandler = new InternalHandler(mHandlerThread.getLooper());
710 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700711
Jeremy Joslin79294842014-12-03 17:15:28 -0800712 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
713 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
714
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900715 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900716
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700717 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700718 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800719 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700720 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700721 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700722 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700723
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600725 mPolicyManager.setConnectivityListener(mPolicyListener);
726 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 } catch (RemoteException e) {
728 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700729 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 }
731
732 final PowerManager powerManager = (PowerManager) context.getSystemService(
733 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700734 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
735 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
736 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800737 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700738
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700739 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700740
Wink Saville51f456f2013-04-23 14:26:51 -0700741 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900742 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700743 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700744 String[] naStrings = context.getResources().getStringArray(
745 com.android.internal.R.array.networkAttributes);
746 for (String naString : naStrings) {
747 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700748 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700749 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700750 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800751 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700752 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700753 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700754 }
Wink Saville51f456f2013-04-23 14:26:51 -0700755 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
756 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
757 n.type);
758 continue;
759 }
Wink Saville975c8482011-04-07 14:23:45 -0700760 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800761 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700762 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 continue;
764 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700765 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700766
Wink Saville975c8482011-04-07 14:23:45 -0700767 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700768 mNetworksDefined++;
769 } catch(Exception e) {
770 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700771 }
772 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700773
774 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
775 if (mNetConfigs[TYPE_VPN] == null) {
776 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
777 // don't need to add TYPE_VPN to mNetConfigs.
778 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
779 mNetworksDefined++; // used only in the log() statement below.
780 }
781
Wink Saville5e56bc52013-07-29 15:00:57 -0700782 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700783
Robert Greenwalt50393202011-06-21 17:26:14 -0700784 mProtectedNetworks = new ArrayList<Integer>();
785 int[] protectedNetworks = context.getResources().getIntArray(
786 com.android.internal.R.array.config_protectedNetworks);
787 for (int p : protectedNetworks) {
788 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
789 mProtectedNetworks.add(p);
790 } else {
791 if (DBG) loge("Ignoring protectedNetwork " + p);
792 }
793 }
794
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900795 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
796 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700797
Christopher Wiley497c1472016-10-11 13:26:03 -0700798 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
799 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800800
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700801 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
802
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700803 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700804 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100805 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700806 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700807 intentFilter.addAction(Intent.ACTION_USER_ADDED);
808 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000809 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700810 mContext.registerReceiverAsUser(
811 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000812 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
813 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900814
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700815 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700816 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700817 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700818 } catch (RemoteException e) {
819 loge("Error registering observer :" + e);
820 }
821
Erik Klineda4bfa82015-04-30 12:58:40 +0900822 mSettingsObserver = new SettingsObserver(mContext, mHandler);
823 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800824
John Spurlockbf991a82013-06-24 14:20:23 -0400825 mDataConnectionStats = new DataConnectionStats(mContext);
826 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400827
Jason Monkdecd2952013-10-10 14:02:51 -0400828 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700829
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400830 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900831
832 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900833 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
834 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900835
836 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
837 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
838 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
839 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
840 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
841 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
842 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900843
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900844 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900845 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900846 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700848
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900849 private NetworkRequest createInternetRequestForTransport(
850 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900851 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900852 netCap.addCapability(NET_CAPABILITY_INTERNET);
853 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900854 if (transportType > -1) {
855 netCap.addTransportType(transportType);
856 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900857 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900858 }
859
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900860 // Used only for testing.
861 // TODO: Delete this and either:
862 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
863 // changing ContentResolver to make registerContentObserver non-final).
864 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
865 // by subclassing SettingsObserver.
866 @VisibleForTesting
867 void updateMobileDataAlwaysOn() {
868 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
869 }
870
Erik Klineda4bfa82015-04-30 12:58:40 +0900871 private void handleMobileDataAlwaysOn() {
872 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900873 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
875 if (enable == isEnabled) {
876 return; // Nothing to do.
877 }
878
879 if (enable) {
880 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900881 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900882 } else {
883 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
884 }
885 }
886
887 private void registerSettingsCallbacks() {
888 // Watch for global HTTP proxy changes.
889 mSettingsObserver.observe(
890 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
891 EVENT_APPLY_GLOBAL_HTTP_PROXY);
892
893 // Watch for whether or not to keep mobile data always on.
894 mSettingsObserver.observe(
895 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
896 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
897 }
898
Robert Greenwalt34524f02014-05-18 16:22:10 -0700899 private synchronized int nextNetworkRequestId() {
900 return mNextNetworkRequestId++;
901 }
902
Paul Jensen67b0b072015-06-10 11:22:17 -0400903 @VisibleForTesting
904 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400905 synchronized (mNetworkForNetId) {
906 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
907 int netId = mNextNetId;
908 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
909 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500910 if (!mNetIdInUse.get(netId)) {
911 mNetIdInUse.put(netId, true);
912 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400913 }
914 }
915 }
916 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700917 }
918
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600919 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600921 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
922 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600924 state = nai.getNetworkState();
925 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600927 final NetworkInfo info = new NetworkInfo(networkType, 0,
928 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
930 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600931 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
932 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600934 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 return state;
936 } else {
937 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400939 }
940
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
942 if (network == null) {
943 return null;
944 }
945 synchronized (mNetworkForNetId) {
946 return mNetworkForNetId.get(network.netId);
947 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600948 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900950 private Network[] getVpnUnderlyingNetworks(int uid) {
951 if (!mLockdownEnabled) {
952 int user = UserHandle.getUserId(uid);
953 synchronized (mVpns) {
954 Vpn vpn = mVpns.get(user);
955 if (vpn != null && vpn.appliesToUid(uid)) {
956 return vpn.getUnderlyingNetworks();
957 }
958 }
959 }
960 return null;
961 }
962
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400964 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800965
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900966 final Network[] networks = getVpnUnderlyingNetworks(uid);
967 if (networks != null) {
968 // getUnderlyingNetworks() returns:
969 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
970 // empty array => the VPN explicitly said "no default network".
971 // non-empty array => the VPN specified one or more default networks; we use the
972 // first one.
973 if (networks.length > 0) {
974 nai = getNetworkAgentInfoForNetwork(networks[0]);
975 } else {
976 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800977 }
978 }
979
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800980 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600981 return nai.getNetworkState();
982 } else {
983 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800984 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400985 }
986
987 /**
988 * Check if UID should be blocked from using the network with the given LinkProperties.
989 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600990 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
991 boolean ignoreBlocked) {
992 // Networks aren't blocked when ignoring blocked status
993 if (ignoreBlocked) return false;
994 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700995 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600996
997 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700998 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700999
Robin Lee17e61832016-05-09 13:46:28 +01001000 synchronized (mVpns) {
1001 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1002 if (vpn != null && vpn.isBlockingUid(uid)) {
1003 return true;
1004 }
1005 }
1006
Robert Greenwalt12e67352014-05-13 21:41:06 -07001007 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001008 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001010 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001011 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001012
Felipe Lemed31a97f2016-05-06 14:53:50 -07001013 boolean allowed = true;
1014 // Check Data Saver Mode first...
1015 if (networkMetered) {
1016 if ((uidRules & RULE_REJECT_METERED) != 0) {
1017 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1018 // Explicitly blacklisted.
1019 allowed = false;
1020 } else {
1021 allowed = !mRestrictBackground
1022 || (uidRules & RULE_ALLOW_METERED) != 0
1023 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1024 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1025 + " mRestrictBackground=" + mRestrictBackground
1026 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1027 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1028 + ": " + allowed);
1029 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001030 }
Felipe Leme781ba142016-05-09 16:24:48 -07001031 // ...then power restrictions.
1032 if (allowed) {
1033 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001034 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001035 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001036 }
1037 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001038 }
1039
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001040 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001041 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1042 return;
1043 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001044 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001045 synchronized (mBlockedAppUids) {
1046 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001047 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001048 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001049 blocked = false;
1050 } else {
1051 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001052 }
1053 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001054 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1055 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1056 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001057 }
1058
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001059 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1061 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1062 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1063 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001065 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1067
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001068 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001069 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 if (mLockdownTracker != null) {
1072 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001073 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001074
1075 // TODO: apply metered state closer to NetworkAgentInfo
1076 final long token = Binder.clearCallingIdentity();
1077 try {
1078 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1079 } catch (RemoteException e) {
1080 } finally {
1081 Binder.restoreCallingIdentity(token);
1082 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001083 }
1084
1085 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 * Return NetworkInfo for the active (i.e., connected) network interface.
1087 * It is assumed that at most one network is active at a time. If more
1088 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001089 * @return the info for the active network, or {@code null} if none is
1090 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001094 enforceAccessPermission();
1095 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001097 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001098 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1099 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
1101
Paul Jensen31a94f42015-02-13 14:18:39 -05001102 @Override
1103 public Network getActiveNetwork() {
1104 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001106 }
1107
1108 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001110 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001111 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001112 }
1113
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001115 final int user = UserHandle.getUserId(uid);
1116 int vpnNetId = NETID_UNSET;
1117 synchronized (mVpns) {
1118 final Vpn vpn = mVpns.get(user);
1119 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1120 }
1121 NetworkAgentInfo nai;
1122 if (vpnNetId != NETID_UNSET) {
1123 synchronized (mNetworkForNetId) {
1124 nai = mNetworkForNetId.get(vpnNetId);
1125 }
1126 if (nai != null) return nai.network;
1127 }
1128 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 if (nai != null
1130 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1131 nai = null;
1132 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001133 return nai != null ? nai.network : null;
1134 }
1135
Lorenzo Colitti18660282016-07-04 12:55:44 +09001136 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001137 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1138 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 final int uid = Binder.getCallingUid();
1140 NetworkState state = getUnfilteredActiveNetworkState(uid);
1141 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001142 }
1143
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001147 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001149 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 }
1151
1152 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 public NetworkInfo getNetworkInfo(int networkType) {
1154 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001156 if (getVpnUnderlyingNetworks(uid) != null) {
1157 // A VPN is active, so we may need to return one of its underlying networks. This
1158 // information is not available in LegacyTypeTracker, so we have to get it from
1159 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001161 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001164 }
1165 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001166 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001175 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001177 return state.networkInfo;
1178 } else {
1179 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001180 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001181 }
1182
1183 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 public NetworkInfo[] getAllNetworkInfo() {
1185 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001186 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001187 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1188 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 NetworkInfo info = getNetworkInfo(networkType);
1190 if (info != null) {
1191 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001194 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001197 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001198 public Network getNetworkForType(int networkType) {
1199 enforceAccessPermission();
1200 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001201 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1202 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001204 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001206 }
1207
1208 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001209 public Network[] getAllNetworks() {
1210 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001211 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001212 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001213 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001214 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001216 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001217 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 }
1219
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001220 @Override
1221 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1222 // The basic principle is: if an app's traffic could possibly go over a
1223 // network, without the app doing anything multinetwork-specific,
1224 // (hence, by "default"), then include that network's capabilities in
1225 // the array.
1226 //
1227 // In the normal case, app traffic only goes over the system's default
1228 // network connection, so that's the only network returned.
1229 //
1230 // With a VPN in force, some app traffic may go into the VPN, and thus
1231 // over whatever underlying networks the VPN specifies, while other app
1232 // traffic may go over the system default network (e.g.: a split-tunnel
1233 // VPN, or an app disallowed by the VPN), so the set of networks
1234 // returned includes the VPN's underlying networks and the system
1235 // default.
1236 enforceAccessPermission();
1237
1238 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1239
1240 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001241 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001242 if (nc != null) {
1243 result.put(nai.network, nc);
1244 }
1245
1246 if (!mLockdownEnabled) {
1247 synchronized (mVpns) {
1248 Vpn vpn = mVpns.get(userId);
1249 if (vpn != null) {
1250 Network[] networks = vpn.getUnderlyingNetworks();
1251 if (networks != null) {
1252 for (Network network : networks) {
1253 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001254 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001255 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001256 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001257 }
1258 }
1259 }
1260 }
1261 }
1262 }
1263
1264 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1265 out = result.values().toArray(out);
1266 return out;
1267 }
1268
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001269 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001270 public boolean isNetworkSupported(int networkType) {
1271 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001272 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001273 }
1274
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001275 /**
1276 * Return LinkProperties for the active (i.e., connected) default
1277 * network interface. It is assumed that at most one default network
1278 * is active at a time. If more than one is active, it is indeterminate
1279 * which will be returned.
1280 * @return the ip properties for the active network, or {@code null} if
1281 * none is active
1282 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001283 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001284 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001285 enforceAccessPermission();
1286 final int uid = Binder.getCallingUid();
1287 NetworkState state = getUnfilteredActiveNetworkState(uid);
1288 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001289 }
1290
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001291 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001292 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001294 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1295 if (nai != null) {
1296 synchronized (nai) {
1297 return new LinkProperties(nai.linkProperties);
1298 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001299 }
1300 return null;
1301 }
1302
Robert Greenwalt12e67352014-05-13 21:41:06 -07001303 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001304 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001305 public LinkProperties getLinkProperties(Network network) {
1306 enforceAccessPermission();
Hugo Benichi29551722017-04-06 16:01:44 +09001307 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1308 }
1309
1310 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1311 if (nai == null) {
1312 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001313 }
Hugo Benichi29551722017-04-06 16:01:44 +09001314 synchronized (nai) {
1315 return new LinkProperties(nai.linkProperties);
1316 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 }
1318
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001319 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001320 if (nai != null) {
1321 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001322 if (nai.networkCapabilities != null) {
1323 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001324 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 }
1326 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001327 return null;
1328 }
1329
1330 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001331 public NetworkCapabilities getNetworkCapabilities(Network network) {
1332 enforceAccessPermission();
1333 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1334 }
1335
1336 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001337 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001338 // Require internal since we're handing out IMSI details
1339 enforceConnectivityInternalPermission();
1340
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001341 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001342 for (Network network : getAllNetworks()) {
1343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1344 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001345 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001346 }
1347 }
1348 return result.toArray(new NetworkState[result.size()]);
1349 }
1350
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001351 @Override
1352 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1353 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001355 final long token = Binder.clearCallingIdentity();
1356 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1358 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001359 try {
1360 return mPolicyManager.getNetworkQuotaInfo(state);
1361 } catch (RemoteException e) {
1362 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001363 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001364 return null;
1365 } finally {
1366 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001367 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001368 }
1369
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001370 @Override
1371 public boolean isActiveNetworkMetered() {
1372 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001373
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001374 final NetworkInfo info = getActiveNetworkInfo();
1375 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001376 }
1377
Jeff Sharkey216c1812012-08-05 14:29:23 -07001378 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1379 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001380 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001381 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001382 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001383 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001384 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001385
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 * Ensure that a network route exists to deliver traffic to the specified
1388 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001389 * @param networkType the type of the network over which traffic to the
1390 * specified host is to be routed
1391 * @param hostAddress the IP address of the host to which the route is
1392 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 * @return {@code true} on success, {@code false} on failure
1394 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001395 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001396 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001398 if (mProtectedNetworks.contains(networkType)) {
1399 enforceConnectivityInternalPermission();
1400 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001401
Chad Brubakerc0234532014-02-14 13:24:29 -08001402 InetAddress addr;
1403 try {
1404 addr = InetAddress.getByAddress(hostAddress);
1405 } catch (UnknownHostException e) {
1406 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1407 return false;
1408 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001411 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 return false;
1413 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001414
1415 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1416 if (nai == null) {
1417 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1418 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1419 } else {
1420 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1421 }
1422 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001423 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001424
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001425 DetailedState netState;
1426 synchronized (nai) {
1427 netState = nai.networkInfo.getDetailedState();
1428 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001429
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001430 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001431 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001432 log("requestRouteToHostAddress on down network "
1433 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001434 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001435 }
1436 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001439 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001440 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001441 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001442 LinkProperties lp;
1443 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001444 synchronized (nai) {
1445 lp = nai.linkProperties;
1446 netId = nai.network.netId;
1447 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001448 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001449 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1450 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001451 } finally {
1452 Binder.restoreCallingIdentity(token);
1453 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001454 }
1455
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001456 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001457 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001458 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001459 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001460 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001461 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001462 if (bestRoute.getGateway().equals(addr)) {
1463 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001464 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001465 } else {
1466 // if we will connect to this through another route, add a direct route
1467 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001468 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001469 }
1470 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001471 if (DBG) log("Adding legacy route " + bestRoute +
1472 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001473 try {
1474 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1475 } catch (Exception e) {
1476 // never crash - catch them all
1477 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001478 return false;
1479 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001480 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001483 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1484 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001485 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001486 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001488 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001489 }
1490
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001491 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001492 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001493 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001494 if (oldRules == uidRules) return;
1495
Felipe Leme781ba142016-05-09 16:24:48 -07001496 if (uidRules == RULE_NONE) {
1497 mUidRules.delete(uid);
1498 } else {
1499 mUidRules.put(uid, uidRules);
1500 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001501 }
1502
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001503 // TODO: notify UID when it has requested targeted updates
1504 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001505
1506 @Override
1507 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001508 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001509 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001510 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001511 }
1512
1513 synchronized (mRulesLock) {
1514 mMeteredIfaces.clear();
1515 for (String iface : meteredIfaces) {
1516 mMeteredIfaces.add(iface);
1517 }
1518 }
1519 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001520
1521 @Override
1522 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1523 // caller is NPMS, since we only register with them
1524 if (LOGD_RULES) {
1525 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1526 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001527
1528 synchronized (mRulesLock) {
1529 mRestrictBackground = restrictBackground;
1530 }
1531
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001532 if (restrictBackground) {
1533 log("onRestrictBackgroundChanged(true): disabling tethering");
1534 mTethering.untetherAll();
1535 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001536 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001537
1538 @Override
1539 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1540 if (LOGD_RULES) {
1541 // caller is NPMS, since we only register with them
1542 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1543 + whitelisted + ")");
1544 }
1545 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001546 @Override
1547 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1548 if (LOGD_RULES) {
1549 // caller is NPMS, since we only register with them
1550 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1551 + blacklisted + ")");
1552 }
1553 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001554 };
1555
Robin Lee3b3dd942015-05-12 18:14:58 +01001556 /**
1557 * Require that the caller is either in the same user or has appropriate permission to interact
1558 * across users.
1559 *
1560 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1561 */
1562 private void enforceCrossUserPermission(int userId) {
1563 if (userId == UserHandle.getCallingUserId()) {
1564 // Not a cross-user call.
1565 return;
1566 }
1567 mContext.enforceCallingOrSelfPermission(
1568 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1569 "ConnectivityService");
1570 }
1571
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001572 private void enforceInternetPermission() {
1573 mContext.enforceCallingOrSelfPermission(
1574 android.Manifest.permission.INTERNET,
1575 "ConnectivityService");
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001579 mContext.enforceCallingOrSelfPermission(
1580 android.Manifest.permission.ACCESS_NETWORK_STATE,
1581 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
1584 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001585 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001588 private void enforceTetherAccessPermission() {
1589 mContext.enforceCallingOrSelfPermission(
1590 android.Manifest.permission.ACCESS_NETWORK_STATE,
1591 "ConnectivityService");
1592 }
1593
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001594 private void enforceConnectivityInternalPermission() {
1595 mContext.enforceCallingOrSelfPermission(
1596 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1597 "ConnectivityService");
1598 }
1599
Hugo Benichi514da602016-07-19 15:59:27 +09001600 private void enforceConnectivityRestrictedNetworksPermission() {
1601 try {
1602 mContext.enforceCallingOrSelfPermission(
1603 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1604 "ConnectivityService");
1605 return;
1606 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1607 enforceConnectivityInternalPermission();
1608 }
1609
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001610 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001611 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001612 }
1613
Lorenzo Colitti18660282016-07-04 12:55:44 +09001614 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001615 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001616 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001617 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001618 }
1619
1620 private void sendInetConditionBroadcast(NetworkInfo info) {
1621 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1622 }
1623
Wink Saville628b0852011-08-04 15:01:58 -07001624 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001625 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001626 info = new NetworkInfo(info);
1627 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001628 }
1629
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001630 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001631 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001632 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 if (info.isFailover()) {
1634 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1635 info.setFailover(false);
1636 }
1637 if (info.getReason() != null) {
1638 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1639 }
1640 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001641 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1642 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001644 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001645 return intent;
1646 }
1647
1648 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1649 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1650 }
1651
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001652 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001653 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1654 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1655 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001656 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001657 final long ident = Binder.clearCallingIdentity();
1658 try {
1659 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1660 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1661 } finally {
1662 Binder.restoreCallingIdentity(ident);
1663 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001664 }
1665
Mike Lockwood0f79b542009-08-14 14:18:49 -04001666 private void sendStickyBroadcast(Intent intent) {
1667 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001668 if (!mSystemReady) {
1669 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001670 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001672 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001673 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001674 }
1675
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001676 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001677 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001678 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001679 final NetworkInfo ni = intent.getParcelableExtra(
1680 ConnectivityManager.EXTRA_NETWORK_INFO);
1681 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1682 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1683 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001684 } else {
1685 BroadcastOptions opts = BroadcastOptions.makeBasic();
1686 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1687 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001688 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001689 final IBatteryStats bs = BatteryStatsService.getService();
1690 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001691 bs.noteConnectivityChanged(intent.getIntExtra(
1692 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1693 ni != null ? ni.getState().toString() : "?");
1694 } catch (RemoteException e) {
1695 }
1696 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001697 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001698 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001699 } finally {
1700 Binder.restoreCallingIdentity(ident);
1701 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001702 }
1703 }
1704
1705 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001706 loadGlobalProxy();
1707
Mike Lockwood0f79b542009-08-14 14:18:49 -04001708 synchronized(this) {
1709 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001710 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001711 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001712 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001713 }
1714 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001715 // load the global proxy at startup
1716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001717
Robin Lee244ce8e2016-01-05 18:03:46 +00001718 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1719 // for user to unlock device too.
1720 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001721
Erik Klineda4bfa82015-04-30 12:58:40 +09001722 // Configure whether mobile data is always on.
1723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1724
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001726
1727 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001731 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001732 *
1733 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001734 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001735 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001736 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1737 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001738
1739 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001741
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 if (networkAgent.networkCapabilities.hasTransport(
1743 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001744 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1745 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001746 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001747 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 } else if (networkAgent.networkCapabilities.hasTransport(
1749 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001750 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1751 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001752 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001754 } else {
1755 // do not track any other networks
1756 timeout = 0;
1757 }
1758
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001760 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001761 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001762 } catch (Exception e) {
1763 // You shall not crash!
1764 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001765 }
1766 }
1767 }
1768
1769 /**
1770 * Remove data activity tracking when network disconnects.
1771 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1773 final String iface = networkAgent.linkProperties.getInterfaceName();
1774 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001775
Robert Greenwalt7b816022014-04-18 15:25:25 -07001776 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1777 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001778 try {
1779 // the call fails silently if no idletimer setup for this interface
1780 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001781 } catch (Exception e) {
1782 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001783 }
1784 }
1785 }
1786
1787 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001788 * Reads the network specific MTU size from reources.
1789 * and set it on it's iface.
1790 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1792 final String iface = newLp.getInterfaceName();
1793 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001794 if (oldLp == null && mtu == 0) {
1795 // Silently ignore unset MTU value.
1796 return;
1797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1799 if (VDBG) log("identical MTU - not setting");
1800 return;
1801 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001802 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001803 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001804 return;
1805 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001806
w1997615afd812014-08-05 15:18:11 -07001807 // Cannot set MTU without interface name
1808 if (TextUtils.isEmpty(iface)) {
1809 loge("Setting MTU size with null iface.");
1810 return;
1811 }
1812
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001814 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 mNetd.setMtu(iface, mtu);
1816 } catch (Exception e) {
1817 Slog.e(TAG, "exception in setMtu()" + e);
1818 }
1819 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001820
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001821 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001822 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1823
1824 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001825 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001826 protected MockableSystemProperties getSystemProperties() {
1827 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001828 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001829
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001830 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1831 if (isDefaultNetwork(nai) == false) {
1832 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001833 }
1834
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1836 String[] values = null;
1837 if (tcpBufferSizes != null) {
1838 values = tcpBufferSizes.split(",");
1839 }
1840
1841 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001842 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1844 values = tcpBufferSizes.split(",");
1845 }
1846
1847 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1848
1849 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001850 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001851
1852 final String prefix = "/sys/kernel/ipv4/tcp_";
1853 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1854 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1855 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1856 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1857 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1858 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1859 mCurrentTcpBufferSizes = tcpBufferSizes;
1860 } catch (IOException e) {
1861 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001862 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001863
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001864 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001865 Settings.Global.TCP_DEFAULT_INIT_RWND,
1866 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001867 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1868 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001869 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001870 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001871 }
1872
Mattias Falk8b47b362011-08-23 14:15:13 +02001873 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001874 /*
1875 * Tell the VMs to toss their DNS caches
1876 */
1877 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1878 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001879 /*
1880 * Connectivity events can happen before boot has completed ...
1881 */
1882 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001883 final long ident = Binder.clearCallingIdentity();
1884 try {
1885 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1886 } finally {
1887 Binder.restoreCallingIdentity(ident);
1888 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001889 }
1890
Robert Greenwalt562cc542014-05-15 18:07:26 -07001891 @Override
1892 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001893 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001894 NETWORK_RESTORE_DELAY_PROP_NAME);
1895 if(restoreDefaultNetworkDelayStr != null &&
1896 restoreDefaultNetworkDelayStr.length() != 0) {
1897 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001898 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001899 } catch (NumberFormatException e) {
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001902 // if the system property isn't set, use the value for the apn type
1903 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1904
1905 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1906 (mNetConfigs[networkType] != null)) {
1907 ret = mNetConfigs[networkType].restoreTime;
1908 }
1909 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001912 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001913 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001914 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001915 }
1916 return false;
1917 }
1918
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001919 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1920 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1921 final long DIAG_TIME_MS = 5000;
1922 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1923 // Start gathering diagnostic information.
1924 netDiags.add(new NetworkDiagnostics(
1925 nai.network,
1926 new LinkProperties(nai.linkProperties), // Must be a copy.
1927 DIAG_TIME_MS));
1928 }
1929
1930 for (NetworkDiagnostics netDiag : netDiags) {
1931 pw.println();
1932 netDiag.waitForMeasurements();
1933 netDiag.dump(pw);
1934 }
1935 }
1936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001938 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1939 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001940 if (mContext.checkCallingOrSelfPermission(
1941 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001943 pw.println("Permission Denial: can't dump ConnectivityService " +
1944 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1945 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 return;
1947 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001949 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001950 dumpNetworkDiagnostics(pw);
1951 return;
1952 }
Erik Kline379747a2015-06-05 17:47:34 +09001953
Lorenzo Colittie3805462015-06-03 11:18:24 +09001954 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001955 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001956 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001957 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001958 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001959 pw.println();
1960
Paul Jensen85cf78e2015-06-25 13:25:07 -04001961 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001962 pw.print("Active default network: ");
1963 if (defaultNai == null) {
1964 pw.println("none");
1965 } else {
1966 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001968 pw.println();
1969
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001970 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001971 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001972 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1973 pw.println(nai.toString());
1974 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001975 pw.println(String.format(
1976 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1977 nai.numForegroundNetworkRequests(),
1978 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1979 nai.numBackgroundNetworkRequests(),
1980 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001982 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1983 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001984 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.decreaseIndent();
1986 pw.println("Lingered:");
1987 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001988 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001989 pw.decreaseIndent();
1990 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001991 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001992 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001994
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001995 pw.println("Metered Interfaces:");
1996 pw.increaseIndent();
1997 for (String value : mMeteredIfaces) {
1998 pw.println(value);
1999 }
2000 pw.decreaseIndent();
2001 pw.println();
2002
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002003 pw.print("Restrict background: ");
2004 pw.println(mRestrictBackground);
2005 pw.println();
2006
Felipe Leme46c4fc32016-05-04 09:21:43 -07002007 pw.println("Status for known UIDs:");
2008 pw.increaseIndent();
2009 final int size = mUidRules.size();
2010 for (int i = 0; i < size; i++) {
2011 final int uid = mUidRules.keyAt(i);
2012 pw.print("UID=");
2013 pw.print(uid);
2014 final int uidRules = mUidRules.get(uid, RULE_NONE);
2015 pw.print(" rules=");
2016 pw.print(uidRulesToString(uidRules));
2017 pw.println();
2018 }
2019 pw.println();
2020 pw.decreaseIndent();
2021
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002022 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002023 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002024 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2025 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002026 }
2027 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002028 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002029
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002030 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002031
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002032 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002033 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002034
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002035 pw.println();
2036 mKeepaliveTracker.dump(pw);
2037
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002038 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002039 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002040
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002041 if (argsContain(args, "--short") == false) {
2042 pw.println();
2043 synchronized (mValidationLogs) {
2044 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002045 for (ValidationLog p : mValidationLogs) {
2046 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002047 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002048 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002049 pw.decreaseIndent();
2050 }
2051 }
Erik Kline7523eb32015-07-09 18:24:03 +09002052
2053 pw.println();
2054 pw.println("mNetworkRequestInfoLogs (most recent first):");
2055 pw.increaseIndent();
2056 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2057 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002058
2059 pw.println();
2060 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2061 pw.increaseIndent();
2062 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2063 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002064
2065 pw.println();
2066 pw.println("NetTransition WakeLock activity (most recent first):");
2067 pw.increaseIndent();
2068 mWakelockLogs.reverseDump(fd, pw, args);
2069 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002073 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002074 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002075 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 if (officialNai != null && officialNai.equals(nai)) return true;
2077 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002078 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002079 " - " + nai);
2080 }
2081 return false;
2082 }
2083
Robert Greenwalt42acef32009-08-12 16:08:25 -07002084 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002085 private class NetworkStateTrackerHandler extends Handler {
2086 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002087 super(looper);
2088 }
2089
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002090 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002092 default:
2093 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002094 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002095 handleAsyncChannelHalfConnect(msg);
2096 break;
2097 }
2098 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2099 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2100 if (nai != null) nai.asyncChannel.disconnect();
2101 break;
2102 }
2103 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2104 handleAsyncChannelDisconnected(msg);
2105 break;
2106 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002107 }
2108 return true;
2109 }
2110
2111 private void maybeHandleNetworkAgentMessage(Message msg) {
2112 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2113 if (nai == null) {
2114 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002115 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002116 }
2117 return;
2118 }
2119
2120 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002122 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2123 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002124 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2125 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002127 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002128 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002129 break;
2130 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002132 if (VDBG) {
2133 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002134 "; created=" + nai.created +
2135 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002136 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002137 LinkProperties oldLp = nai.linkProperties;
2138 synchronized (nai) {
2139 nai.linkProperties = (LinkProperties)msg.obj;
2140 }
Robin Lee585e2482016-05-01 23:00:00 +01002141 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 break;
2143 }
2144 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 updateNetworkInfo(nai, info);
2147 break;
2148 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002149 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002150 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002151 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002152 break;
2153 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002154 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002155 try {
2156 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002157 } catch (Exception e) {
2158 // Never crash!
2159 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002160 }
2161 break;
2162 }
2163 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002164 try {
2165 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002166 } catch (Exception e) {
2167 // Never crash!
2168 loge("Exception in removeVpnUidRanges: " + e);
2169 }
2170 break;
2171 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002172 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002173 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2174 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002175 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002176 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002177 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002178 break;
2179 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002180 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002181 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2182 break;
2183 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 }
2185 }
2186
2187 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2188 switch (msg.what) {
2189 default:
2190 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002191 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002192 final NetworkAgentInfo nai;
2193 synchronized (mNetworkForNetId) {
2194 nai = mNetworkForNetId.get(msg.arg2);
2195 }
2196 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002197 final boolean valid =
2198 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002199 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002200 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2201 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002202 if (valid != nai.lastValidated) {
2203 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002204 nai.lastValidated = valid;
2205 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002206 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002207 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2208 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002209 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002210 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002211 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002212 Bundle redirectUrlBundle = new Bundle();
2213 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002214 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002215 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002216 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002217 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002218 if (wasValidated && !nai.lastValidated) {
2219 handleNetworkUnvalidated(nai);
2220 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002221 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 break;
2223 }
Paul Jensen869868be2014-05-15 10:33:05 -04002224 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002225 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002226 final boolean visible = (msg.arg1 != 0);
2227 final NetworkAgentInfo nai;
2228 synchronized (mNetworkForNetId) {
2229 nai = mNetworkForNetId.get(netId);
2230 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002231 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002232 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002233 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002234 nai.lastCaptivePortalDetected = visible;
2235 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002236 if (nai.lastCaptivePortalDetected &&
2237 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2238 if (DBG) log("Avoiding captive portal network: " + nai.name());
2239 nai.asyncChannel.sendMessage(
2240 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2241 teardownUnneededNetwork(nai);
2242 break;
2243 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002244 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002245 }
2246 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002247 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002248 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002249 if (nai == null) {
2250 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2251 break;
2252 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002253 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002254 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002255 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002256 }
Paul Jensen869868be2014-05-15 10:33:05 -04002257 }
Paul Jensen869868be2014-05-15 10:33:05 -04002258 break;
2259 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002260 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002261 return true;
2262 }
2263
Calvin On1f64f3f2016-10-11 15:10:46 -07002264 private int getCaptivePortalMode() {
2265 return Settings.Global.getInt(mContext.getContentResolver(),
2266 Settings.Global.CAPTIVE_PORTAL_MODE,
2267 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2268 }
2269
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002270 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2271 switch (msg.what) {
2272 default:
2273 return false;
2274 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2275 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2276 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2277 handleLingerComplete(nai);
2278 }
2279 break;
2280 }
2281 }
2282 return true;
2283 }
2284
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002285 @Override
2286 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002287 if (!maybeHandleAsyncChannelMessage(msg) &&
2288 !maybeHandleNetworkMonitorMessage(msg) &&
2289 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002290 maybeHandleNetworkAgentMessage(msg);
2291 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002292 }
2293 }
2294
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002295 private void updateLingerState(NetworkAgentInfo nai, long now) {
2296 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2297 // 2. If the network was lingering and there are now requests, unlinger it.
2298 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2299 // one lingered request, start lingering.
2300 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002301 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002302 if (DBG) log("Unlingering " + nai.name());
2303 nai.unlinger();
2304 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002305 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002306 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002307 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002308 nai.linger();
2309 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2310 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2311 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002312 }
2313
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 private void handleAsyncChannelHalfConnect(Message msg) {
2315 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002316 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2318 if (VDBG) log("NetworkFactory connected");
2319 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002320 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002321 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002322 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002323 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002324 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002325 }
2326 } else {
2327 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002328 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002329 }
2330 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2331 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2332 if (VDBG) log("NetworkAgent connected");
2333 // A network agent has requested a connection. Establish the connection.
2334 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2335 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2336 } else {
2337 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002338 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002339 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002340 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002341 synchronized (mNetworkForNetId) {
2342 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002343 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002344 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002345 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002346 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002348 }
2349 }
2350 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002351
Robert Greenwalt7b816022014-04-18 15:25:25 -07002352 private void handleAsyncChannelDisconnected(Message msg) {
2353 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2354 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002355 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002356 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002357 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002358 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002359 // TODO - if we move the logic to the network agent (have them disconnect
2360 // because they lost all their requests or because their score isn't good)
2361 // then they would disconnect organically, report their new state and then
2362 // disconnect the channel.
2363 if (nai.networkInfo.isConnected()) {
2364 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2365 null, null);
2366 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002367 final boolean wasDefault = isDefaultNetwork(nai);
2368 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002369 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002370 // Log default network disconnection before required book-keeping.
2371 // Let rematchAllNetworksAndRequests() below record a new default network event
2372 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2373 // whose timestamps tell how long it takes to recover a default network.
2374 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002375 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002376 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002377 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2378 // by other networks that are already connected. Perhaps that can be done by
2379 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2380 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002382 mKeepaliveTracker.handleStopAllKeepalives(nai,
2383 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002384 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002385 mNetworkAgentInfos.remove(msg.replyTo);
2386 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002387 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002388 // Remove the NetworkAgent, but don't mark the netId as
2389 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002390 mNetworkForNetId.remove(nai.network.netId);
2391 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002392 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002393 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2394 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2396 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2397 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002398 sendUpdatedScoreToFactories(request, 0);
2399 }
2400 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002401 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002402 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002404 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002405 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002406 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002407 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002408 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002409 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002410 if (nai.created) {
2411 // Tell netd to clean up the configuration for this network
2412 // (routing rules, DNS, etc).
2413 // This may be slow as it requires a lot of netd shelling out to ip and
2414 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2415 // after we've rematched networks with requests which should make a potential
2416 // fallback network the default or requested a new network from the
2417 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2418 // long time.
2419 try {
2420 mNetd.removeNetwork(nai.network.netId);
2421 } catch (Exception e) {
2422 loge("Exception removing network: " + e);
2423 }
2424 }
2425 synchronized (mNetworkForNetId) {
2426 mNetIdInUse.delete(nai.network.netId);
2427 }
2428 } else {
2429 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2430 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002431 }
2432 }
2433
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002434 // If this method proves to be too slow then we can maintain a separate
2435 // pendingIntent => NetworkRequestInfo map.
2436 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2437 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2438 Intent intent = pendingIntent.getIntent();
2439 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2440 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2441 if (existingPendingIntent != null &&
2442 existingPendingIntent.getIntent().filterEquals(intent)) {
2443 return entry.getValue();
2444 }
2445 }
2446 return null;
2447 }
2448
2449 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2450 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2451
2452 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2453 if (existingRequest != null) { // remove the existing request.
2454 if (DBG) log("Replacing " + existingRequest.request + " with "
2455 + nri.request + " because their intents matched.");
2456 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2457 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002458 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002459 }
2460
Erik Klineda4bfa82015-04-30 12:58:40 +09002461 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002462 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002463 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002464 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002465 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002466 if (nri.request.networkCapabilities.hasSignalStrength() &&
2467 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2468 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002469 }
2470 }
2471 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002472 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002473 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002474 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002475 }
2476 }
2477
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002478 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2479 int callingUid) {
2480 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2481 if (nri != null) {
2482 handleReleaseNetworkRequest(nri.request, callingUid);
2483 }
2484 }
2485
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002486 // Determines whether the network is the best (or could become the best, if it validated), for
2487 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2488 // on the value of reason:
2489 //
2490 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2491 // then it should be torn down.
2492 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2493 // then it should be lingered.
2494 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2495 final int numRequests;
2496 switch (reason) {
2497 case TEARDOWN:
2498 numRequests = nai.numRequestNetworkRequests();
2499 break;
2500 case LINGER:
2501 numRequests = nai.numForegroundNetworkRequests();
2502 break;
2503 default:
2504 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2505 return true;
2506 }
2507
2508 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002509 return false;
2510 }
Paul Jensene0988542015-06-25 15:30:08 -04002511 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002512 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2513 // Background requests don't affect lingering.
2514 continue;
2515 }
2516
Paul Jensene0988542015-06-25 15:30:08 -04002517 // If this Network is already the highest scoring Network for a request, or if
2518 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002519 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002520 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002521 // Note that this catches two important cases:
2522 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2523 // is currently satisfying the request. This is desirable when
2524 // cellular ends up validating but WiFi does not.
2525 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002526 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002527 // WiFi ends up validating and out scoring cellular.
2528 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2529 nai.getCurrentScoreAsValidated())) {
2530 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002531 }
2532 }
Paul Jensene0988542015-06-25 15:30:08 -04002533 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002534 }
2535
Erik Klineacdd6392016-07-07 16:50:58 +09002536 private NetworkRequestInfo getNriForAppRequest(
2537 NetworkRequest request, int callingUid, String requestedOperation) {
2538 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2539
Robert Greenwalt9258c642014-03-26 16:47:06 -07002540 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002541 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002542 log(String.format("UID %d attempted to %s for unowned request %s",
2543 callingUid, requestedOperation, nri));
2544 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002545 }
Erik Klineacdd6392016-07-07 16:50:58 +09002546 }
2547
2548 return nri;
2549 }
2550
Erik Kline3841a482015-11-25 12:49:38 +09002551 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2552 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2553 nri.request.requestId) == null) {
2554 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2555 }
2556 }
2557
Erik Klineacdd6392016-07-07 16:50:58 +09002558 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2559 final NetworkRequestInfo nri = getNriForAppRequest(
2560 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002561 if (nri != null) {
2562 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2563 }
2564 }
Erik Klineacdd6392016-07-07 16:50:58 +09002565
Erik Kline3841a482015-11-25 12:49:38 +09002566 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2567 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2568 if (VDBG || (DBG && nri.request.isRequest())) {
2569 log("releasing " + nri.request + " (" + logCallbackType + ")");
2570 }
Erik Klineacdd6392016-07-07 16:50:58 +09002571 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002572 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002573 synchronized (mUidToNetworkRequestCount) {
2574 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2575 if (requests < 1) {
2576 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2577 nri.mUid);
2578 } else if (requests == 1) {
2579 mUidToNetworkRequestCount.removeAt(
2580 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2581 } else {
2582 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2583 }
2584 }
2585 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2586 if (nri.request.isRequest()) {
2587 boolean wasKept = false;
2588 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2589 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002590 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002591 nai.removeRequest(nri.request.requestId);
2592 if (VDBG) {
2593 log(" Removing from current network " + nai.name() +
2594 ", leaving " + nai.numNetworkRequests() + " requests.");
2595 }
2596 // If there are still lingered requests on this network, don't tear it down,
2597 // but resume lingering instead.
2598 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002599 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002600 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2601 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002602 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002603 wasKept = true;
2604 }
2605 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002606 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2607 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002608 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002609 }
Erik Klineacdd6392016-07-07 16:50:58 +09002610 }
2611
2612 // TODO: remove this code once we know that the Slog.wtf is never hit.
2613 //
2614 // Find all networks that are satisfying this request and remove the request
2615 // from their request lists.
2616 // TODO - it's my understanding that for a request there is only a single
2617 // network satisfying it, so this loop is wasteful
2618 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2619 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2620 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2621 otherNai.name() + ", but mNetworkAgentInfos says " +
2622 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002623 }
2624 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002625
Erik Klineacdd6392016-07-07 16:50:58 +09002626 // Maintain the illusion. When this request arrived, we might have pretended
2627 // that a network connected to serve it, even though the network was already
2628 // connected. Now that this request has gone away, we might have to pretend
2629 // that the network disconnected. LegacyTypeTracker will generate that
2630 // phantom disconnect for this type.
2631 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2632 boolean doRemove = true;
2633 if (wasKept) {
2634 // check if any of the remaining requests for this network are for the
2635 // same legacy type - if so, don't remove the nai
2636 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2637 NetworkRequest otherRequest = nai.requestAt(i);
2638 if (otherRequest.legacyType == nri.request.legacyType &&
2639 otherRequest.isRequest()) {
2640 if (DBG) log(" still have other legacy request - leaving");
2641 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002642 }
2643 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002644 }
2645
Erik Klineacdd6392016-07-07 16:50:58 +09002646 if (doRemove) {
2647 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002648 }
2649 }
Erik Klineacdd6392016-07-07 16:50:58 +09002650
2651 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2652 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2653 nri.request);
2654 }
2655 } else {
2656 // listens don't have a singular affectedNetwork. Check all networks to see
2657 // if this listen request applies and remove it.
2658 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2659 nai.removeRequest(nri.request.requestId);
2660 if (nri.request.networkCapabilities.hasSignalStrength() &&
2661 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2662 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2663 }
2664 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002665 }
Erik Kline3841a482015-11-25 12:49:38 +09002666 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002667 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002668
Lorenzo Colitti18660282016-07-04 12:55:44 +09002669 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002670 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2671 enforceConnectivityInternalPermission();
2672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2673 accept ? 1 : 0, always ? 1: 0, network));
2674 }
2675
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002676 @Override
2677 public void setAvoidUnvalidated(Network network) {
2678 enforceConnectivityInternalPermission();
2679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2680 }
2681
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002682 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2683 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2684 " accept=" + accept + " always=" + always);
2685
2686 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2687 if (nai == null) {
2688 // Nothing to do.
2689 return;
2690 }
2691
2692 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002693 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002694 return;
2695 }
2696
2697 if (!nai.networkMisc.explicitlySelected) {
2698 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2699 }
2700
2701 if (accept != nai.networkMisc.acceptUnvalidated) {
2702 int oldScore = nai.getCurrentScore();
2703 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002704 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002705 sendUpdatedScoreToFactories(nai);
2706 }
2707
2708 if (always) {
2709 nai.asyncChannel.sendMessage(
2710 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2711 }
2712
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002713 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002714 // Tell the NetworkAgent to not automatically reconnect to the network.
2715 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2716 // Teardown the nework.
2717 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002718 }
2719
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 }
2721
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002722 private void handleSetAvoidUnvalidated(Network network) {
2723 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2724 if (nai == null || nai.lastValidated) {
2725 // Nothing to do. The network either disconnected or revalidated.
2726 return;
2727 }
2728 if (!nai.avoidUnvalidated) {
2729 int oldScore = nai.getCurrentScore();
2730 nai.avoidUnvalidated = true;
2731 rematchAllNetworksAndRequests(nai, oldScore);
2732 sendUpdatedScoreToFactories(nai);
2733 }
2734 }
2735
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002736 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002737 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002738 mHandler.sendMessageDelayed(
2739 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2740 PROMPT_UNVALIDATED_DELAY_MS);
2741 }
2742
Hugo Benichic8e9e122016-09-14 23:23:08 +00002743 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002744 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002745 }
2746
Erik Kline065ab6e2016-10-02 18:02:14 +09002747 private void rematchForAvoidBadWifiUpdate() {
2748 rematchAllNetworksAndRequests(null, 0);
2749 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2750 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2751 sendUpdatedScoreToFactories(nai);
2752 }
2753 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002754 }
2755
Erik Kline065ab6e2016-10-02 18:02:14 +09002756 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002757 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002758 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002759 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002760 if (!configRestrict) {
2761 pw.println("Bad Wi-Fi avoidance: unrestricted");
2762 return;
2763 }
2764
2765 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2766 pw.increaseIndent();
2767 pw.println("Config restrict: " + configRestrict);
2768
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002769 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002770 String description;
2771 // Can't use a switch statement because strings are legal case labels, but null is not.
2772 if ("0".equals(value)) {
2773 description = "get stuck";
2774 } else if (value == null) {
2775 description = "prompt";
2776 } else if ("1".equals(value)) {
2777 description = "avoid";
2778 } else {
2779 description = value + " (?)";
2780 }
2781 pw.println("User setting: " + description);
2782 pw.println("Network overrides:");
2783 pw.increaseIndent();
2784 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2785 if (nai.avoidUnvalidated) {
2786 pw.println(nai.name());
2787 }
2788 }
2789 pw.decreaseIndent();
2790 pw.decreaseIndent();
2791 }
2792
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002793 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2794 final String action;
2795 switch (type) {
2796 case NO_INTERNET:
2797 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2798 break;
2799 case LOST_INTERNET:
2800 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2801 break;
2802 default:
2803 Slog.wtf(TAG, "Unknown notification type " + type);
2804 return;
2805 }
2806
2807 Intent intent = new Intent(action);
2808 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2809 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2810 intent.setClassName("com.android.settings",
2811 "com.android.settings.wifi.WifiNoInternetDialog");
2812
2813 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2814 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2815 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2816 }
2817
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002818 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002819 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002820 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2821
2822 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2823 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002824 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002825 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002826 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2827 return;
2828 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002829 showValidationNotification(nai, NotificationType.NO_INTERNET);
2830 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002831
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002832 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2833 NetworkCapabilities nc = nai.networkCapabilities;
2834 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002835
Erik Kline065ab6e2016-10-02 18:02:14 +09002836 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002837 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002838 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2839 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002840 }
2841
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09002842 @Override
2843 public int getMultipathPreference(Network network) {
2844 enforceAccessPermission();
2845
2846 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2847 if (nai != null && !nai.networkInfo.isMetered()) {
2848 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2849 }
2850
2851 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2852 }
2853
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002854 private class InternalHandler extends Handler {
2855 public InternalHandler(Looper looper) {
2856 super(looper);
2857 }
2858
2859 @Override
2860 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002861 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002862 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002863 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002864 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002865 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002866 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002867 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002868 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002869 break;
2870 }
Jason Monkdecd2952013-10-10 14:02:51 -04002871 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002872 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002873 break;
2874 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002875 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002876 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2877 break;
2878 }
2879 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2880 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002881 break;
2882 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002883 case EVENT_REGISTER_NETWORK_AGENT: {
2884 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2885 break;
2886 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002887 case EVENT_REGISTER_NETWORK_REQUEST:
2888 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002889 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002890 break;
2891 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002892 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2893 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002894 handleRegisterNetworkRequestWithIntent(msg);
2895 break;
2896 }
Erik Kline3841a482015-11-25 12:49:38 +09002897 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2898 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2899 handleTimedOutNetworkRequest(nri);
2900 break;
2901 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002902 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2903 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2904 break;
2905 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002906 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002907 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002908 break;
2909 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002910 case EVENT_SET_ACCEPT_UNVALIDATED: {
2911 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2912 break;
2913 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002914 case EVENT_SET_AVOID_UNVALIDATED: {
2915 handleSetAvoidUnvalidated((Network) msg.obj);
2916 break;
2917 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002918 case EVENT_PROMPT_UNVALIDATED: {
2919 handlePromptUnvalidated((Network) msg.obj);
2920 break;
2921 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002922 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2923 handleMobileDataAlwaysOn();
2924 break;
2925 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002926 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2927 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2928 mKeepaliveTracker.handleStartKeepalive(msg);
2929 break;
2930 }
2931 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2932 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2933 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2934 int slot = msg.arg1;
2935 int reason = msg.arg2;
2936 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2937 break;
2938 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002939 case EVENT_SYSTEM_READY: {
2940 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2941 nai.networkMonitor.systemReady = true;
2942 }
2943 break;
2944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946 }
2947 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002948
2949 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002950 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002951 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002952 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002953 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002954 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002955 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002956 } else {
2957 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2958 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002959 }
2960
2961 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002962 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002963 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002964 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002965
2966 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002967 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002968 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002969 } else {
2970 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2971 }
2972 }
2973
2974 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002975 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002976 public int getLastTetherError(String iface) {
2977 enforceTetherAccessPermission();
2978
2979 if (isTetheringSupported()) {
2980 return mTethering.getLastTetherError(iface);
2981 } else {
2982 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2983 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002984 }
2985
2986 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002987 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002988 public String[] getTetherableUsbRegexs() {
2989 enforceTetherAccessPermission();
2990 if (isTetheringSupported()) {
2991 return mTethering.getTetherableUsbRegexs();
2992 } else {
2993 return new String[0];
2994 }
2995 }
2996
Lorenzo Colitti18660282016-07-04 12:55:44 +09002997 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002998 public String[] getTetherableWifiRegexs() {
2999 enforceTetherAccessPermission();
3000 if (isTetheringSupported()) {
3001 return mTethering.getTetherableWifiRegexs();
3002 } else {
3003 return new String[0];
3004 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003005 }
3006
Lorenzo Colitti18660282016-07-04 12:55:44 +09003007 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003008 public String[] getTetherableBluetoothRegexs() {
3009 enforceTetherAccessPermission();
3010 if (isTetheringSupported()) {
3011 return mTethering.getTetherableBluetoothRegexs();
3012 } else {
3013 return new String[0];
3014 }
3015 }
3016
Lorenzo Colitti18660282016-07-04 12:55:44 +09003017 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003018 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003019 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003020 if (isTetheringSupported()) {
3021 return mTethering.setUsbTethering(enable);
3022 } else {
3023 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3024 }
3025 }
3026
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003027 // TODO - move iface listing, queries, etc to new module
3028 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003029 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003030 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003031 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003032 return mTethering.getTetherableIfaces();
3033 }
3034
Lorenzo Colitti18660282016-07-04 12:55:44 +09003035 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003036 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003037 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003038 return mTethering.getTetheredIfaces();
3039 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003040
Lorenzo Colitti18660282016-07-04 12:55:44 +09003041 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003042 public String[] getTetheringErroredIfaces() {
3043 enforceTetherAccessPermission();
3044 return mTethering.getErroredIfaces();
3045 }
3046
Lorenzo Colitti18660282016-07-04 12:55:44 +09003047 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003048 public String[] getTetheredDhcpRanges() {
3049 enforceConnectivityInternalPermission();
3050 return mTethering.getTetheredDhcpRanges();
3051 }
3052
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003053 // if ro.tether.denied = true we default to no tethering
3054 // gservices could set the secure setting to 1 though to enable it on a build where it
3055 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003056 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003057 public boolean isTetheringSupported() {
3058 enforceTetherAccessPermission();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09003059 int defaultVal = (mSystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003060 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003061 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3062 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003063
3064 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3065 boolean adminUser = false;
3066 final long token = Binder.clearCallingIdentity();
3067 try {
3068 adminUser = mUserManager.isAdminUser();
3069 } finally {
3070 Binder.restoreCallingIdentity(token);
3071 }
3072
3073 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09003074 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003075 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003076
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003077 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003078 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003079 ConnectivityManager.enforceTetherChangePermission(mContext);
3080 if (!isTetheringSupported()) {
3081 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3082 return;
3083 }
3084 mTethering.startTethering(type, receiver, showProvisioningUi);
3085 }
3086
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003087 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003088 public void stopTethering(int type) {
3089 ConnectivityManager.enforceTetherChangePermission(mContext);
3090 mTethering.stopTethering(type);
3091 }
3092
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003093 // Called when we lose the default network and have no replacement yet.
3094 // This will automatically be cleared after X seconds or a new default network
3095 // becomes CONNECTED, whichever happens first. The timer is started by the
3096 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003097 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003098 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003099 if (mNetTransitionWakeLock.isHeld()) {
3100 return;
3101 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003102 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003103 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003104 mWakelockLogs.log("ACQUIRE for " + forWhom);
3105 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3106 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003107 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003108
Hugo Benichi4c31b342017-03-30 23:18:10 +09003109 // Called when we gain a new default network to release the network transition wakelock in a
3110 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3111 // message is cancelled.
3112 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003113 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003114 if (!mNetTransitionWakeLock.isHeld()) {
3115 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003116 }
3117 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003118 // Cancel self timeout on wakelock hold.
3119 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3120 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3121 mHandler.sendMessageDelayed(msg, 1000);
3122 }
3123
3124 // Called when either message of ensureNetworkTransitionWakelock or
3125 // scheduleReleaseNetworkTransitionWakelock is processed.
3126 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3127 String event = eventName(eventId);
3128 synchronized (this) {
3129 if (!mNetTransitionWakeLock.isHeld()) {
3130 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3131 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3132 return;
3133 }
3134 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003135 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003136 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003137 }
3138
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003139 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003140 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003141 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003142 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003143 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003144 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003145 }
3146
Lorenzo Colitti18660282016-07-04 12:55:44 +09003147 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003148 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003149 enforceAccessPermission();
3150 enforceInternetPermission();
3151
Hugo Benichi29551722017-04-06 16:01:44 +09003152 // TODO: execute this logic on ConnectivityService handler.
3153 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003154 if (network == null) {
3155 nai = getDefaultNetwork();
3156 } else {
3157 nai = getNetworkAgentInfoForNetwork(network);
3158 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003159 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3160 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3161 return;
3162 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003163 // Revalidate if the app report does not match our current validated state.
Hugo Benichi29551722017-04-06 16:01:44 +09003164 if (hasConnectivity == nai.lastValidated) {
3165 return;
3166 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003167 final int uid = Binder.getCallingUid();
3168 if (DBG) {
3169 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3170 ") by " + uid);
3171 }
Hugo Benichi29551722017-04-06 16:01:44 +09003172 // Validating a network that has not yet connected could result in a call to
3173 // rematchNetworkAndRequests() which is not meant to work on such networks.
3174 if (!nai.everConnected) {
3175 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003176 }
Hugo Benichi29551722017-04-06 16:01:44 +09003177 LinkProperties lp = getLinkProperties(nai);
3178 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3179 return;
3180 }
3181 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003182 }
3183
Paul Jensencee9b512015-05-06 07:32:40 -04003184 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003185 // this information is already available as a world read/writable jvm property
3186 // so this API change wouldn't have a benifit. It also breaks the passing
3187 // of proxy info to all the JVMs.
3188 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003189 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003190 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003191 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3192 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003193 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003194 }
3195
Lorenzo Colitti18660282016-07-04 12:55:44 +09003196 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003197 public ProxyInfo getProxyForNetwork(Network network) {
3198 if (network == null) return getDefaultProxy();
3199 final ProxyInfo globalProxy = getGlobalProxy();
3200 if (globalProxy != null) return globalProxy;
3201 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3202 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3203 // caller may not have.
3204 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3205 if (nai == null) return null;
3206 synchronized (nai) {
3207 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3208 if (proxyInfo == null) return null;
3209 return new ProxyInfo(proxyInfo);
3210 }
3211 }
3212
Paul Jensene0bef712014-12-10 15:12:18 -05003213 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3214 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3215 // proxy is null then there is no proxy in place).
3216 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3217 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3218 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3219 proxy = null;
3220 }
3221 return proxy;
3222 }
3223
3224 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3225 // better for determining if a new proxy broadcast is necessary:
3226 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3227 // avoid unnecessary broadcasts.
3228 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3229 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3230 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3231 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3232 // all set.
3233 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3234 a = canonicalizeProxyInfo(a);
3235 b = canonicalizeProxyInfo(b);
3236 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3237 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3238 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3239 }
3240
Jason Monk207900c2014-04-25 15:00:09 -04003241 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003242 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003243
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003244 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003245 if (proxyProperties == mGlobalProxy) return;
3246 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3247 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3248
3249 String host = "";
3250 int port = 0;
3251 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003252 String pacFileUrl = "";
3253 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003254 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003255 if (!proxyProperties.isValid()) {
3256 if (DBG)
3257 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3258 return;
3259 }
Jason Monk207900c2014-04-25 15:00:09 -04003260 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 host = mGlobalProxy.getHost();
3262 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003263 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003264 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003265 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003266 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003267 } else {
3268 mGlobalProxy = null;
3269 }
3270 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003271 final long token = Binder.clearCallingIdentity();
3272 try {
3273 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3274 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3275 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3276 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003277 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003278 } finally {
3279 Binder.restoreCallingIdentity(token);
3280 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003281
Jason Monkcf0f97a2014-10-02 15:39:38 -04003282 if (mGlobalProxy == null) {
3283 proxyProperties = mDefaultProxy;
3284 }
3285 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003286 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003287 }
3288
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003289 private void loadGlobalProxy() {
3290 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003291 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3292 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3293 String exclList = Settings.Global.getString(res,
3294 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003295 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3296 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003297 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003298 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003299 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003300 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003301 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003302 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003303 if (!proxyProperties.isValid()) {
3304 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3305 return;
3306 }
3307
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003308 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003309 mGlobalProxy = proxyProperties;
3310 }
3311 }
3312 }
3313
Jason Monk207900c2014-04-25 15:00:09 -04003314 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003315 // this information is already available as a world read/writable jvm property
3316 // so this API change wouldn't have a benifit. It also breaks the passing
3317 // of proxy info to all the JVMs.
3318 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003319 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003320 return mGlobalProxy;
3321 }
3322 }
3323
Jason Monk207900c2014-04-25 15:00:09 -04003324 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003325 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003326 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003327 proxy = null;
3328 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003329 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003331 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003332 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003333 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3334 return;
3335 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003336
3337 // This call could be coming from the PacManager, containing the port of the local
3338 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3339 // global (to get the correct local port), and send a broadcast.
3340 // TODO: Switch PacManager to have its own message to send back rather than
3341 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003342 if ((mGlobalProxy != null) && (proxy != null)
3343 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003344 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3345 mGlobalProxy = proxy;
3346 sendProxyBroadcast(mGlobalProxy);
3347 return;
3348 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003349 mDefaultProxy = proxy;
3350
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003351 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003352 if (!mDefaultProxyDisabled) {
3353 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003354 }
3355 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 }
3357
Paul Jensene0bef712014-12-10 15:12:18 -05003358 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3359 // This method gets called when any network changes proxy, but the broadcast only ever contains
3360 // the default proxy (even if it hasn't changed).
3361 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3362 // world where an app might be bound to a non-default network.
3363 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3364 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3365 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3366
3367 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3368 sendProxyBroadcast(getDefaultProxy());
3369 }
3370 }
3371
Robert Greenwalt434203a2010-10-11 16:00:27 -07003372 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003373 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3374 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 if (!TextUtils.isEmpty(proxy)) {
3376 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003377 if (data.length == 0) {
3378 return;
3379 }
3380
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 String proxyHost = data[0];
3382 int proxyPort = 8080;
3383 if (data.length > 1) {
3384 try {
3385 proxyPort = Integer.parseInt(data[1]);
3386 } catch (NumberFormatException e) {
3387 return;
3388 }
3389 }
Jason Monk207900c2014-04-25 15:00:09 -04003390 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003391 setGlobalProxy(p);
3392 }
3393 }
3394
Jason Monk207900c2014-04-25 15:00:09 -04003395 private void sendProxyBroadcast(ProxyInfo proxy) {
3396 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003397 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003398 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003399 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003400 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3401 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003403 final long ident = Binder.clearCallingIdentity();
3404 try {
3405 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3406 } finally {
3407 Binder.restoreCallingIdentity(ident);
3408 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003409 }
3410
3411 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003412 final private HashMap<Uri, Integer> mUriEventMap;
3413 final private Context mContext;
3414 final private Handler mHandler;
3415
3416 SettingsObserver(Context context, Handler handler) {
3417 super(null);
3418 mUriEventMap = new HashMap<Uri, Integer>();
3419 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421 }
3422
Erik Klineda4bfa82015-04-30 12:58:40 +09003423 void observe(Uri uri, int what) {
3424 mUriEventMap.put(uri, what);
3425 final ContentResolver resolver = mContext.getContentResolver();
3426 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003427 }
3428
3429 @Override
3430 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003431 Slog.wtf(TAG, "Should never be reached.");
3432 }
3433
3434 @Override
3435 public void onChange(boolean selfChange, Uri uri) {
3436 final Integer what = mUriEventMap.get(uri);
3437 if (what != null) {
3438 mHandler.obtainMessage(what.intValue()).sendToTarget();
3439 } else {
3440 loge("No matching event to send for URI=" + uri);
3441 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 }
3443 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003444
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003445 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003446 Slog.d(TAG, s);
3447 }
3448
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003449 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003450 Slog.e(TAG, s);
3451 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003452
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003453 private static <T> T checkNotNull(T value, String message) {
3454 if (value == null) {
3455 throw new NullPointerException(message);
3456 }
3457 return value;
3458 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003459
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003460 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003461 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003462 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3463 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3464 *
3465 * @param oldPackage Package name of the application which currently controls VPN, which will
3466 * be replaced. If there is no such application, this should should either be
3467 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3468 * @param newPackage Package name of the application which should gain control of VPN, or
3469 * {@code null} to disable.
3470 * @param userId User for whom to prepare the new VPN.
3471 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003472 * @hide
3473 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003474 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003475 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3476 int userId) {
3477 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003478 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003479
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003480 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003481 Vpn vpn = mVpns.get(userId);
3482 if (vpn != null) {
3483 return vpn.prepare(oldPackage, newPackage);
3484 } else {
3485 return false;
3486 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003487 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003488 }
3489
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003490 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003491 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3492 * This method is used by system-privileged apps.
3493 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3494 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3495 *
3496 * @param packageName The package for which authorization state should change.
3497 * @param userId User for whom {@code packageName} is installed.
3498 * @param authorized {@code true} if this app should be able to start a VPN connection without
3499 * explicit user approval, {@code false} if not.
3500 *
Jeff Davidson05542602014-08-11 14:07:27 -07003501 * @hide
3502 */
3503 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003504 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3505 enforceCrossUserPermission(userId);
3506
Jeff Davidson05542602014-08-11 14:07:27 -07003507 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003508 Vpn vpn = mVpns.get(userId);
3509 if (vpn != null) {
3510 vpn.setPackageAuthorization(packageName, authorized);
3511 }
Jeff Davidson05542602014-08-11 14:07:27 -07003512 }
3513 }
3514
3515 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003516 * Configure a TUN interface and return its file descriptor. Parameters
3517 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003518 * and not available in ConnectivityManager. Permissions are checked in
3519 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003520 * @hide
3521 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003522 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003523 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003524 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 int user = UserHandle.getUserId(Binder.getCallingUid());
3526 synchronized(mVpns) {
3527 return mVpns.get(user).establish(config);
3528 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003529 }
3530
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003531 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003532 * Start legacy VPN, controlling native daemons as needed. Creates a
3533 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003534 */
3535 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003536 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003537 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003538 final LinkProperties egress = getActiveLinkProperties();
3539 if (egress == null) {
3540 throw new IllegalStateException("Missing active network connection");
3541 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003542 int user = UserHandle.getUserId(Binder.getCallingUid());
3543 synchronized(mVpns) {
3544 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3545 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003546 }
3547
3548 /**
3549 * Return the information of the ongoing legacy VPN. This method is used
3550 * by VpnSettings and not available in ConnectivityManager. Permissions
3551 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003552 */
3553 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003554 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3555 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003556
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003557 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003558 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003559 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003560 }
3561
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003562 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003563 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3564 * and not available in ConnectivityManager.
3565 */
3566 @Override
3567 public VpnInfo[] getAllVpnInfo() {
3568 enforceConnectivityInternalPermission();
3569 if (mLockdownEnabled) {
3570 return new VpnInfo[0];
3571 }
3572
3573 synchronized(mVpns) {
3574 List<VpnInfo> infoList = new ArrayList<>();
3575 for (int i = 0; i < mVpns.size(); i++) {
3576 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3577 if (info != null) {
3578 infoList.add(info);
3579 }
3580 }
3581 return infoList.toArray(new VpnInfo[infoList.size()]);
3582 }
3583 }
3584
3585 /**
3586 * @return VPN information for accounting, or null if we can't retrieve all required
3587 * information, e.g primary underlying iface.
3588 */
3589 @Nullable
3590 private VpnInfo createVpnInfo(Vpn vpn) {
3591 VpnInfo info = vpn.getVpnInfo();
3592 if (info == null) {
3593 return null;
3594 }
3595 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3596 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3597 // the underlyingNetworks list.
3598 if (underlyingNetworks == null) {
3599 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3600 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3601 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3602 }
3603 } else if (underlyingNetworks.length > 0) {
3604 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3605 if (linkProperties != null) {
3606 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3607 }
3608 }
3609 return info.primaryUnderlyingIface == null ? null : info;
3610 }
3611
3612 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003613 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3614 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003615 * Permissions are checked in Vpn class.
3616 * @hide
3617 */
3618 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003619 public VpnConfig getVpnConfig(int userId) {
3620 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003621 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003622 Vpn vpn = mVpns.get(userId);
3623 if (vpn != null) {
3624 return vpn.getVpnConfig();
3625 } else {
3626 return null;
3627 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003628 }
3629 }
3630
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003631 @Override
3632 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003633 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3634 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3635 return false;
3636 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003637
3638 // Tear down existing lockdown if profile was removed
3639 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3640 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003641 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3642 if (profileTag == null) {
3643 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3644 return false;
3645 }
3646 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003647 final VpnProfile profile = VpnProfile.decode(
3648 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003649 if (profile == null) {
3650 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3651 setLockdownTracker(null);
3652 return true;
3653 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003654 int user = UserHandle.getUserId(Binder.getCallingUid());
3655 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003656 Vpn vpn = mVpns.get(user);
3657 if (vpn == null) {
3658 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3659 return false;
3660 }
3661 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003662 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003663 } else {
3664 setLockdownTracker(null);
3665 }
3666
3667 return true;
3668 }
3669
3670 /**
3671 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3672 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3673 */
3674 private void setLockdownTracker(LockdownVpnTracker tracker) {
3675 // Shutdown any existing tracker
3676 final LockdownVpnTracker existing = mLockdownTracker;
3677 mLockdownTracker = null;
3678 if (existing != null) {
3679 existing.shutdown();
3680 }
3681
3682 try {
3683 if (tracker != null) {
3684 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003685 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003686 mLockdownTracker = tracker;
3687 mLockdownTracker.init();
3688 } else {
3689 mNetd.setFirewallEnabled(false);
3690 }
3691 } catch (RemoteException e) {
3692 // ignored; NMS lives inside system_server
3693 }
3694 }
3695
3696 private void throwIfLockdownEnabled() {
3697 if (mLockdownEnabled) {
3698 throw new IllegalStateException("Unavailable in lockdown mode");
3699 }
3700 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003701
Robin Lee244ce8e2016-01-05 18:03:46 +00003702 /**
Robin Lee17e61832016-05-09 13:46:28 +01003703 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3704 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003705 *
Robin Lee17e61832016-05-09 13:46:28 +01003706 * @return {@code true} if the service was started, the service was already connected, or there
3707 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003708 */
Robin Lee17e61832016-05-09 13:46:28 +01003709 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003710 synchronized (mVpns) {
3711 Vpn vpn = mVpns.get(userId);
3712 if (vpn == null) {
3713 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3714 // exists already.
3715 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3716 return false;
3717 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003718
Robin Lee812800c2016-05-13 15:38:08 +01003719 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003720 }
3721 }
3722
3723 @Override
Robin Leedc679712016-05-03 13:23:03 +01003724 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003725 enforceConnectivityInternalPermission();
3726 enforceCrossUserPermission(userId);
3727
3728 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3729 if (LockdownVpnTracker.isEnabled()) {
3730 return false;
3731 }
3732
Robin Lee244ce8e2016-01-05 18:03:46 +00003733 synchronized (mVpns) {
3734 Vpn vpn = mVpns.get(userId);
3735 if (vpn == null) {
3736 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3737 return false;
3738 }
Robin Lee17e61832016-05-09 13:46:28 +01003739 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003740 return false;
3741 }
Robin Lee17e61832016-05-09 13:46:28 +01003742 if (!startAlwaysOnVpn(userId)) {
3743 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003744 return false;
3745 }
3746 }
3747 return true;
3748 }
3749
3750 @Override
3751 public String getAlwaysOnVpnPackage(int userId) {
3752 enforceConnectivityInternalPermission();
3753 enforceCrossUserPermission(userId);
3754
3755 synchronized (mVpns) {
3756 Vpn vpn = mVpns.get(userId);
3757 if (vpn == null) {
3758 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3759 return null;
3760 }
3761 return vpn.getAlwaysOnPackage();
3762 }
3763 }
3764
Wink Savilleab9321d2013-06-29 21:10:57 -07003765 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003766 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003767 // TODO: Remove? Any reason to trigger a provisioning check?
3768 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003769 }
3770
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003771 /** Location to an updatable file listing carrier provisioning urls.
3772 * An example:
3773 *
3774 * <?xml version="1.0" encoding="utf-8"?>
3775 * <provisioningUrls>
3776 * <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 -07003777 * </provisioningUrls>
3778 */
3779 private static final String PROVISIONING_URL_PATH =
3780 "/data/misc/radio/provisioning_urls.xml";
3781 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003782
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003783 /** XML tag for root element. */
3784 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3785 /** XML tag for individual url */
3786 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003787 /** XML attribute for mcc */
3788 private static final String ATTR_MCC = "mcc";
3789 /** XML attribute for mnc */
3790 private static final String ATTR_MNC = "mnc";
3791
Paul Jensen434dde82015-06-11 09:43:30 -04003792 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003793 FileReader fileReader = null;
3794 XmlPullParser parser = null;
3795 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003796
3797 try {
3798 fileReader = new FileReader(mProvisioningUrlFile);
3799 parser = Xml.newPullParser();
3800 parser.setInput(fileReader);
3801 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3802
3803 while (true) {
3804 XmlUtils.nextElement(parser);
3805
3806 String element = parser.getName();
3807 if (element == null) break;
3808
Paul Jensen434dde82015-06-11 09:43:30 -04003809 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003810 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3811 try {
3812 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3813 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3814 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3815 parser.next();
3816 if (parser.getEventType() == XmlPullParser.TEXT) {
3817 return parser.getText();
3818 }
3819 }
3820 }
3821 } catch (NumberFormatException e) {
3822 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3823 }
3824 }
3825 }
3826 return null;
3827 } catch (FileNotFoundException e) {
3828 loge("Carrier Provisioning Urls file not found");
3829 } catch (XmlPullParserException e) {
3830 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3831 } catch (IOException e) {
3832 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3833 } finally {
3834 if (fileReader != null) {
3835 try {
3836 fileReader.close();
3837 } catch (IOException e) {}
3838 }
3839 }
3840 return null;
3841 }
3842
Wink Saville42d4f082013-07-20 20:31:59 -07003843 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003844 public String getMobileProvisioningUrl() {
3845 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003846 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003847 if (TextUtils.isEmpty(url)) {
3848 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003849 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003850 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003851 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003852 }
Wink Saville8cf35602013-07-10 23:00:07 -07003853 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003854 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003855 String phoneNumber = mTelephonyManager.getLine1Number();
3856 if (TextUtils.isEmpty(phoneNumber)) {
3857 phoneNumber = "0000000000";
3858 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003859 url = String.format(url,
3860 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3861 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003862 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003863 }
3864
Wink Savilleab9321d2013-06-29 21:10:57 -07003865 return url;
3866 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003867
Wink Saville948282b2013-08-29 08:55:16 -07003868 @Override
3869 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003870 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003871 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003872 final long ident = Binder.clearCallingIdentity();
3873 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003874 // Concatenate the range of types onto the range of NetIDs.
3875 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3876 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003877 } finally {
3878 Binder.restoreCallingIdentity(ident);
3879 }
Wink Saville948282b2013-08-29 08:55:16 -07003880 }
Wink Saville7788c612013-08-29 14:57:08 -07003881
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003882 @Override
3883 public void setAirplaneMode(boolean enable) {
3884 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003885 final long ident = Binder.clearCallingIdentity();
3886 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003887 final ContentResolver cr = mContext.getContentResolver();
3888 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3889 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3890 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003891 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003892 } finally {
3893 Binder.restoreCallingIdentity(ident);
3894 }
3895 }
3896
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003897 private void onUserStart(int userId) {
3898 synchronized(mVpns) {
3899 Vpn userVpn = mVpns.get(userId);
3900 if (userVpn != null) {
3901 loge("Starting user already has a VPN");
3902 return;
3903 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003904 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003905 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003906 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003907 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3908 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003909 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003910 }
3911
3912 private void onUserStop(int userId) {
3913 synchronized(mVpns) {
3914 Vpn userVpn = mVpns.get(userId);
3915 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003916 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003917 return;
3918 }
Robin Lee17e61832016-05-09 13:46:28 +01003919 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003920 mVpns.delete(userId);
3921 }
3922 }
3923
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003924 private void onUserAdded(int userId) {
3925 synchronized(mVpns) {
3926 final int vpnsSize = mVpns.size();
3927 for (int i = 0; i < vpnsSize; i++) {
3928 Vpn vpn = mVpns.valueAt(i);
3929 vpn.onUserAdded(userId);
3930 }
3931 }
3932 }
3933
3934 private void onUserRemoved(int userId) {
3935 synchronized(mVpns) {
3936 final int vpnsSize = mVpns.size();
3937 for (int i = 0; i < vpnsSize; i++) {
3938 Vpn vpn = mVpns.valueAt(i);
3939 vpn.onUserRemoved(userId);
3940 }
3941 }
3942 }
3943
Robin Lee89e7a692016-02-29 14:38:17 +00003944 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003945 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3946 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3947 updateLockdownVpn();
3948 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003949 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003950 }
3951 }
3952
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3954 @Override
3955 public void onReceive(Context context, Intent intent) {
3956 final String action = intent.getAction();
3957 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3958 if (userId == UserHandle.USER_NULL) return;
3959
Robin Lee323f29d2016-05-04 16:38:06 +01003960 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003961 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003962 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003963 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003964 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3965 onUserAdded(userId);
3966 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3967 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003968 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3969 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003970 }
3971 }
3972 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003973
Robin Lee95204e02017-01-27 11:59:22 +00003974 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3975 @Override
3976 public void onReceive(Context context, Intent intent) {
3977 // Try creating lockdown tracker, since user present usually means
3978 // unlocked keystore.
3979 updateLockdownVpn();
3980 mContext.unregisterReceiver(this);
3981 }
3982 };
3983
Robert Greenwalta67be032014-05-16 15:49:14 -07003984 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3985 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3987 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003988
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003989 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3990 // Map from UID to number of NetworkRequests that UID has filed.
3991 @GuardedBy("mUidToNetworkRequestCount")
3992 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3993
Robert Greenwalta67be032014-05-16 15:49:14 -07003994 private static class NetworkFactoryInfo {
3995 public final String name;
3996 public final Messenger messenger;
3997 public final AsyncChannel asyncChannel;
3998
3999 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4000 this.name = name;
4001 this.messenger = messenger;
4002 this.asyncChannel = asyncChannel;
4003 }
4004 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004005
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004006 private void ensureNetworkRequestHasType(NetworkRequest request) {
4007 if (request.type == NetworkRequest.Type.NONE) {
4008 throw new IllegalArgumentException(
4009 "All NetworkRequests in ConnectivityService must have a type");
4010 }
4011 }
4012
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004013 /**
4014 * Tracks info about the requester.
4015 * Also used to notice when the calling process dies so we can self-expire
4016 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004018 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004019 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004020 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 final int mPid;
4023 final int mUid;
4024 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004025
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004026 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004027 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004028 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004029 mPendingIntent = pi;
4030 messenger = null;
4031 mBinder = null;
4032 mPid = getCallingPid();
4033 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004034 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004035 }
4036
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004037 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004038 super();
4039 messenger = m;
4040 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004041 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 mBinder = binder;
4043 mPid = getCallingPid();
4044 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004046 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047
4048 try {
4049 mBinder.linkToDeath(this, 0);
4050 } catch (RemoteException e) {
4051 binderDied();
4052 }
4053 }
4054
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004055 private void enforceRequestCountLimit() {
4056 synchronized (mUidToNetworkRequestCount) {
4057 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4058 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4059 throw new IllegalArgumentException("Too many NetworkRequests filed");
4060 }
4061 mUidToNetworkRequestCount.put(mUid, networkRequests);
4062 }
4063 }
4064
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004066 if (mBinder != null) {
4067 mBinder.unlinkToDeath(this, 0);
4068 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004069 }
4070
4071 public void binderDied() {
4072 log("ConnectivityService NetworkRequestInfo binderDied(" +
4073 request + ", " + mBinder + ")");
4074 releaseNetworkRequest(request);
4075 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004076
4077 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004078 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004079 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004080 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 }
4082
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004083 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4084 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4085 if (badCapability != null) {
4086 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004087 }
4088 }
4089
Erik Kline9d598e12015-07-13 16:37:51 +09004090 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004091 final SortedSet<Integer> thresholds = new TreeSet();
4092 synchronized (nai) {
4093 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4094 if (nri.request.networkCapabilities.hasSignalStrength() &&
4095 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4096 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4097 }
4098 }
4099 }
Erik Kline9d598e12015-07-13 16:37:51 +09004100 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004101 }
4102
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004103 private void updateSignalStrengthThresholds(
4104 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4105 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004106 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004107 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4108
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004109 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004110 String detail;
4111 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4112 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4113 } else {
4114 detail = reason;
4115 }
4116 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4117 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4118 }
4119
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004120 nai.asyncChannel.sendMessage(
4121 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004122 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004123 }
4124
Robert Greenwalt9258c642014-03-26 16:47:06 -07004125 @Override
4126 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004127 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004128 final NetworkRequest.Type type = (networkCapabilities == null)
4129 ? NetworkRequest.Type.TRACK_DEFAULT
4130 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004131 // If the requested networkCapabilities is null, take them instead from
4132 // the default network request. This allows callers to keep track of
4133 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004134 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004135 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4136 enforceAccessPermission();
4137 } else {
4138 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4139 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004140 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4141 // of the app when the request is filed, but we never change the request if the app
4142 // changes network state. http://b/29964605
4143 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004144 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004145 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004146
Etan Cohenba07c8c2017-02-05 10:42:27 -08004147 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 throw new IllegalArgumentException("Bad timeout specified");
4149 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004150
Etan Cohena7434272017-04-03 12:17:51 -07004151 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4152 networkCapabilities.getNetworkSpecifier());
Etan Cohenddb9ef02015-11-18 10:56:15 -08004153
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004154 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004155 nextNetworkRequestId(), type);
4156 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004157 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158
4159 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004160 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004161 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004162 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 }
4164 return networkRequest;
4165 }
4166
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004168 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004169 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004170 } else {
4171 enforceChangePermission();
4172 }
4173 }
4174
fenglub15e72b2015-03-20 11:29:56 -07004175 @Override
fengludb571472015-04-21 17:12:05 -07004176 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004177 enforceAccessPermission();
4178 NetworkAgentInfo nai = null;
4179 if (network == null) {
4180 return false;
4181 }
4182 synchronized (mNetworkForNetId) {
4183 nai = mNetworkForNetId.get(network.netId);
4184 }
4185 if (nai != null) {
4186 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4187 return true;
4188 }
4189 return false;
4190 }
4191
Felipe Lemeee27cab2016-06-20 16:36:29 -07004192 private boolean isSystem(int uid) {
4193 return uid < Process.FIRST_APPLICATION_UID;
4194 }
fenglub15e72b2015-03-20 11:29:56 -07004195
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004197 final int uid = Binder.getCallingUid();
4198 if (isSystem(uid)) {
4199 return;
4200 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004201 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004202 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004203 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204 synchronized(mRulesLock) {
4205 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4206 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004207 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4208 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004210 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004211 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004212 }
4213 }
4214 }
4215
Robert Greenwalt9258c642014-03-26 16:47:06 -07004216 @Override
4217 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4218 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004219 checkNotNull(operation, "PendingIntent cannot be null.");
4220 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4221 enforceNetworkRequestPermissions(networkCapabilities);
4222 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004223 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004224
Etan Cohena7434272017-04-03 12:17:51 -07004225 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4226 networkCapabilities.getNetworkSpecifier());
4227
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004228 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004229 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4230 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004231 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4233 nri));
4234 return networkRequest;
4235 }
4236
Jeremy Joslin79294842014-12-03 17:15:28 -08004237 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4238 mHandler.sendMessageDelayed(
4239 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4240 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4241 }
4242
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004243 @Override
4244 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004245 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004246 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4247 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004248 }
4249
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004250 // In order to implement the compatibility measure for pre-M apps that call
4251 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4252 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4253 // This ensures it has permission to do so.
4254 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4255 if (nc == null) {
4256 return false;
4257 }
4258 int[] transportTypes = nc.getTransportTypes();
4259 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4260 return false;
4261 }
4262 try {
4263 mContext.enforceCallingOrSelfPermission(
4264 android.Manifest.permission.ACCESS_WIFI_STATE,
4265 "ConnectivityService");
4266 } catch (SecurityException e) {
4267 return false;
4268 }
4269 return true;
4270 }
4271
Robert Greenwalt9258c642014-03-26 16:47:06 -07004272 @Override
4273 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4274 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004275 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4276 enforceAccessPermission();
4277 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004278
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004279 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4280 if (!ConnectivityManager.checkChangePermission(mContext)) {
4281 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4282 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4283 // onLost and onAvailable callbacks when networks move in and out of the background.
4284 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4285 // can't request networks.
4286 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4287 }
4288
Etan Cohena7434272017-04-03 12:17:51 -07004289 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4290 networkCapabilities.getNetworkSpecifier());
4291
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004292 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004293 NetworkRequest.Type.LISTEN);
4294 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004295 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004296
4297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4298 return networkRequest;
4299 }
4300
4301 @Override
4302 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4303 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004304 checkNotNull(operation, "PendingIntent cannot be null.");
4305 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4306 enforceAccessPermission();
4307 }
4308
Etan Cohena7434272017-04-03 12:17:51 -07004309 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4310 networkCapabilities.getNetworkSpecifier());
4311
Erik Kline7523eb32015-07-09 18:24:03 +09004312 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004313 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4314 NetworkRequest.Type.LISTEN);
4315 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004316 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004317
4318 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 }
4320
Erik Klineacdd6392016-07-07 16:50:58 +09004321 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004323 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004324 mHandler.sendMessage(mHandler.obtainMessage(
4325 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 }
4327
4328 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004329 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004330 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004331 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4332 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004333 }
4334
Robert Greenwalta67be032014-05-16 15:49:14 -07004335 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004336 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004337 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4338 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4339 }
4340
4341 @Override
4342 public void unregisterNetworkFactory(Messenger messenger) {
4343 enforceConnectivityInternalPermission();
4344 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4345 }
4346
4347 private void handleUnregisterNetworkFactory(Messenger messenger) {
4348 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4349 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004350 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004351 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004353 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004354 }
4355
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 /**
4357 * NetworkAgentInfo supporting a request by requestId.
4358 * These have already been vetted (their Capabilities satisfy the request)
4359 * and the are the highest scored network available.
4360 * the are keyed off the Requests requestId.
4361 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004362 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4364 new SparseArray<NetworkAgentInfo>();
4365
Paul Jensen31a94f42015-02-13 14:18:39 -05004366 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4367 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004368 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4369 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004370 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4371 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4372 // there may not be a strict 1:1 correlation between the two.
4373 @GuardedBy("mNetworkForNetId")
4374 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004375
Robert Greenwalt7b816022014-04-18 15:25:25 -07004376 // NetworkAgentInfo keyed off its connecting messenger
4377 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004378 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4380 new HashMap<Messenger, NetworkAgentInfo>();
4381
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004382 @GuardedBy("mBlockedAppUids")
4383 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4384
Paul Jensen2c311d62014-11-17 12:34:51 -05004385 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386 private final NetworkRequest mDefaultRequest;
4387
Erik Klineda4bfa82015-04-30 12:58:40 +09004388 // Request used to optionally keep mobile data active even when higher
4389 // priority networks like Wi-Fi are active.
4390 private final NetworkRequest mDefaultMobileDataRequest;
4391
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004392 private NetworkAgentInfo getDefaultNetwork() {
4393 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4394 }
4395
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004396 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004397 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004398 }
4399
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004400 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4401 return nri.request.requestId == mDefaultRequest.requestId;
4402 }
4403
Paul Jensen31a94f42015-02-13 14:18:39 -05004404 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004406 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 enforceConnectivityInternalPermission();
4408
Paul Jensen2c311d62014-11-17 12:34:51 -05004409 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4410 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004411 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004412 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4413 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004414 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004415 synchronized (this) {
4416 nai.networkMonitor.systemReady = mSystemReady;
4417 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004418 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4419 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004420 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004422 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 }
4424
4425 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4426 if (VDBG) log("Got NetworkAgent Messenger");
4427 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004428 synchronized (mNetworkForNetId) {
4429 mNetworkForNetId.put(na.network.netId, na);
4430 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4432 NetworkInfo networkInfo = na.networkInfo;
4433 na.networkInfo = null;
4434 updateNetworkInfo(na, networkInfo);
4435 }
4436
4437 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4438 LinkProperties newLp = networkAgent.linkProperties;
4439 int netId = networkAgent.network.netId;
4440
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004441 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4442 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004443 if (networkAgent.clatd != null) {
4444 networkAgent.clatd.fixupLinkProperties(oldLp);
4445 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004446
Paul Jensen992f2522014-04-28 10:33:11 -04004447 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 updateMtu(newLp, oldLp);
4449 // TODO - figure out what to do for clat
4450// for (LinkProperties lp : newLp.getStackedLinks()) {
4451// updateMtu(lp, null);
4452// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004453 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004454
Erik Kline94887872016-04-05 13:30:49 +09004455 updateRoutes(newLp, oldLp, netId);
4456 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004457
Paul Jensen3b759822014-05-13 11:44:01 -04004458 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004459 if (isDefaultNetwork(networkAgent)) {
4460 handleApplyDefaultProxy(newLp.getHttpProxy());
4461 } else {
4462 updateProxy(newLp, oldLp, networkAgent);
4463 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004464 // TODO - move this check to cover the whole function
4465 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004466 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004467 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4468 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004469
4470 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004471 }
4472
Lorenzo Colitti95439462014-10-09 13:44:48 +09004473 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4474 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4475 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004476
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004477 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004478 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4479 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004480 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004481 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004482 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004483 }
Paul Jensen992f2522014-04-28 10:33:11 -04004484
4485 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4486 CompareResult<String> interfaceDiff = new CompareResult<String>();
4487 if (oldLp != null) {
4488 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4489 } else if (newLp != null) {
4490 interfaceDiff.added = newLp.getAllInterfaceNames();
4491 }
4492 for (String iface : interfaceDiff.added) {
4493 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004494 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004495 mNetd.addInterfaceToNetwork(iface, netId);
4496 } catch (Exception e) {
4497 loge("Exception adding interface: " + e);
4498 }
4499 }
4500 for (String iface : interfaceDiff.removed) {
4501 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004502 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004503 mNetd.removeInterfaceFromNetwork(iface, netId);
4504 } catch (Exception e) {
4505 loge("Exception removing interface: " + e);
4506 }
4507 }
4508 }
4509
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004510 /**
4511 * Have netd update routes from oldLp to newLp.
4512 * @return true if routes changed between oldLp and newLp
4513 */
4514 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4516 if (oldLp != null) {
4517 routeDiff = oldLp.compareAllRoutes(newLp);
4518 } else if (newLp != null) {
4519 routeDiff.added = newLp.getAllRoutes();
4520 }
4521
4522 // add routes before removing old in case it helps with continuous connectivity
4523
4524 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4525 for (RouteInfo route : routeDiff.added) {
4526 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004527 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528 try {
4529 mNetd.addRoute(netId, route);
4530 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004531 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4532 loge("Exception in addRoute for non-gateway: " + e);
4533 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 }
4535 }
4536 for (RouteInfo route : routeDiff.added) {
4537 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004538 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 try {
4540 mNetd.addRoute(netId, route);
4541 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004542 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4543 loge("Exception in addRoute for gateway: " + e);
4544 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 }
4546 }
4547
4548 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004549 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004550 try {
4551 mNetd.removeRoute(netId, route);
4552 } catch (Exception e) {
4553 loge("Exception in removeRoute: " + e);
4554 }
4555 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004556 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 }
Erik Kline41368502015-06-17 13:19:54 +09004558
Erik Kline94887872016-04-05 13:30:49 +09004559 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4560 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4561 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562 }
Erik Kline94887872016-04-05 13:30:49 +09004563
4564 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004565 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004566 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004567 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004568 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4569 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004570 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004571 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004572 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4573 if (defaultNai != null && defaultNai.network.netId == netId) {
4574 setDefaultDnsSystemProperties(dnses);
4575 }
Erik Kline94887872016-04-05 13:30:49 +09004576 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004577 }
4578
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004579 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4580 int last = 0;
4581 for (InetAddress dns : dnses) {
4582 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004583 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004584 }
4585 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004586 setNetDnsProperty(i, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004587 }
4588 mNumDnsEntries = last;
4589 }
4590
Erik Kline4edba012017-04-07 15:29:29 +09004591 private void setNetDnsProperty(int which, String value) {
4592 final String key = "net.dns" + which;
4593 // Log and forget errors setting unsupported properties.
4594 try {
4595 mSystemProperties.set(key, value);
4596 } catch (Exception e) {
4597 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4598 }
4599 }
4600
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004601 private String getNetworkPermission(NetworkCapabilities nc) {
4602 // TODO: make these permission strings AIDL constants instead.
4603 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4604 return NetworkManagementService.PERMISSION_SYSTEM;
4605 }
4606 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4607 return NetworkManagementService.PERMISSION_NETWORK;
4608 }
4609 return null;
4610 }
4611
Paul Jensen3d194ea2015-06-16 14:27:36 -04004612 /**
4613 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4614 * augmented with any stateful capabilities implied from {@code networkAgent}
4615 * (e.g., validated status and captive portal status).
4616 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004617 * @param oldScore score of the network before any of the changes that prompted us
4618 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004619 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004620 * @param networkCapabilities the new network capabilities.
4621 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004622 private void updateCapabilities(
4623 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004624 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4625 networkCapabilities)) {
4626 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4627 + nai.networkCapabilities + " -> " + networkCapabilities);
4628 }
4629
Paul Jensen3d194ea2015-06-16 14:27:36 -04004630 // Don't modify caller's NetworkCapabilities.
4631 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004632 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004633 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4634 } else {
4635 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4636 }
Paul Jensene0988542015-06-25 15:30:08 -04004637 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004638 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4639 } else {
4640 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4641 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004642 if (nai.isBackgroundNetwork()) {
4643 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4644 } else {
4645 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4646 }
4647
4648 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4649
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004650 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4651 final String newPermission = getNetworkPermission(networkCapabilities);
4652 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004653 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004654 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004655 } catch (RemoteException e) {
4656 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004657 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004658 }
4659
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004660 final NetworkCapabilities prevNc = nai.networkCapabilities;
4661 synchronized (nai) {
4662 nai.networkCapabilities = networkCapabilities;
4663 }
4664 if (nai.getCurrentScore() == oldScore &&
4665 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4666 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4667 // the change we're processing can't affect any requests, it can only affect the listens
4668 // on this network. We might have been called by rematchNetworkAndRequests when a
4669 // network changed foreground state.
4670 processListenRequests(nai, true);
4671 } else {
4672 // If the requestable capabilities have changed or the score changed, we can't have been
4673 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004674 rematchAllNetworksAndRequests(nai, oldScore);
4675 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004676 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 }
4678
Paul Jensenc8b9a742014-09-30 15:37:41 -04004679 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004680 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4681 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004682 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004683 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004684 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4685 }
4686 }
4687
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4689 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004690 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004691 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4692 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004693 }
4694 }
4695
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004696 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4697 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004698 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004699 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004700 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4701 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004702 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004703 sendIntent(nri.mPendingIntent, intent);
4704 }
4705 // else not handled
4706 }
4707
4708 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4709 mPendingIntentWakeLock.acquire();
4710 try {
4711 if (DBG) log("Sending " + pendingIntent);
4712 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4713 } catch (PendingIntent.CanceledException e) {
4714 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4715 mPendingIntentWakeLock.release();
4716 releasePendingNetworkRequest(pendingIntent);
4717 }
4718 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4719 }
4720
4721 @Override
4722 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4723 String resultData, Bundle resultExtras) {
4724 if (DBG) log("Finished sending " + pendingIntent);
4725 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004726 // Release with a delay so the receiving client has an opportunity to put in its
4727 // own request.
4728 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004729 }
4730
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004732 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004733 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004734 Bundle bundle = new Bundle();
4735 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4736 new NetworkRequest(nri.request));
4737 Message msg = Message.obtain();
4738 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4739 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4740 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4741 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004742 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004743 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004744 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004745 break;
4746 }
4747 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4748 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4749 new NetworkCapabilities(networkAgent.networkCapabilities));
4750 break;
4751 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004752 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004753 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4754 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) {
4762 log("sending notification " + notifyTypeToName(notificationType) +
4763 " for " + nri.request);
4764 }
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
Paul Jensenc8b9a742014-09-30 15:37:41 -04004772 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004773 if (nai.numRequestNetworkRequests() != 0) {
4774 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4775 NetworkRequest nr = nai.requestAt(i);
4776 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004777 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004778 loge("Dead network still had at least " + nr);
4779 break;
4780 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004781 }
4782 nai.asyncChannel.disconnect();
4783 }
4784
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4786 if (oldNetwork == null) {
4787 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4788 return;
4789 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004790 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004791
4792 // If we get here it means that the last linger timeout for this network expired. So there
4793 // must be no other active linger timers, and we must stop lingering.
4794 oldNetwork.clearLingerState();
4795
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004796 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004797 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004798 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004799 } else {
4800 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004801 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4802 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004803 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004804 }
4805
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004806 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004807 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004808 setupDataActivityTracking(newNetwork);
4809 try {
4810 mNetd.setDefaultNetId(newNetwork.network.netId);
4811 } catch (Exception e) {
4812 loge("Exception setting default network :" + e);
4813 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004814 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004815 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004816 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004817 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004818 }
4819
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004820 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004821 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4822 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4823 NetworkRequest nr = nri.request;
4824 if (!nr.isListen()) continue;
4825 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4826 nai.removeRequest(nri.request.requestId);
4827 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4828 }
4829 }
4830
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004831 if (capabilitiesChanged) {
4832 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4833 }
4834
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004835 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4836 NetworkRequest nr = nri.request;
4837 if (!nr.isListen()) continue;
4838 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4839 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004840 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004841 }
4842 }
4843 }
4844
Paul Jensen2161a8e2014-09-11 11:00:39 -04004845 // Handles a network appearing or improving its score.
4846 //
4847 // - Evaluates all current NetworkRequests that can be
4848 // satisfied by newNetwork, and reassigns to newNetwork
4849 // any such requests for which newNetwork is the best.
4850 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004851 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004852 // needed. A network is needed if it is the best network for
4853 // one or more NetworkRequests, or if it is a VPN.
4854 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004855 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004856 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004857 //
4858 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4859 // networks that have no chance (i.e. even if validated)
4860 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004861 //
4862 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4863 // it does not remove NetworkRequests that other Networks could better satisfy.
4864 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4865 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4866 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004867 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004868 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004869 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4870 // performed to tear down unvalidated networks that have no chance (i.e. even if
4871 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004872 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004873 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004874 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004875 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004876 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004877 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004878
4879 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4880 final int score = newNetwork.getCurrentScore();
4881
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004882 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883
Paul Jensen2161a8e2014-09-11 11:00:39 -04004884 // Find and migrate to this Network any NetworkRequests for
4885 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004887 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004888 NetworkCapabilities nc = newNetwork.networkCapabilities;
4889 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004890 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004891 // Process requests in the first pass and listens in the second pass. This allows us to
4892 // change a network's capabilities depending on which requests it has. This is only
4893 // correct if the change in capabilities doesn't affect whether the network satisfies
4894 // requests or not, and doesn't affect the network's score.
4895 if (nri.request.isListen()) continue;
4896
Paul Jensencf4c2c62015-07-01 14:16:32 -04004897 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4898 final boolean satisfies = newNetwork.satisfies(nri.request);
4899 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004900 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004901 log("Network " + newNetwork.name() + " was already satisfying" +
4902 " request " + nri.request.requestId + ". No change.");
4903 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004904 keep = true;
4905 continue;
4906 }
4907
4908 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004909 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004910 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004911 // next check if it's better than any current network we're using for
4912 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004913 if (VDBG) {
4914 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004915 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004916 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004918 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004919 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004920 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004921 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004922 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004923 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004924 affectedNetworks.add(currentNetwork);
4925 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004926 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004927 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004928 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004929 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004930 if (!newNetwork.addRequest(nri.request)) {
4931 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4932 }
4933 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004935 // Tell NetworkFactories about the new score, so they can stop
4936 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004937 // TODO - this could get expensive if we have alot of requests for this
4938 // network. Think about if there is a way to reduce this. Push
4939 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004940 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004941 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004943 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004944 if (currentNetwork != null) {
4945 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4946 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004947 }
4948 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004949 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004950 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4951 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004952 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004953 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4954 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4955 // This means this code doesn't have to handle the case where "currentNetwork" no
4956 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4957 if (DBG) {
4958 log("Network " + newNetwork.name() + " stopped satisfying" +
4959 " request " + nri.request.requestId);
4960 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004961 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004962 if (currentNetwork == newNetwork) {
4963 mNetworkForRequestId.remove(nri.request.requestId);
4964 sendUpdatedScoreToFactories(nri.request, 0);
4965 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004966 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4967 newNetwork.name() +
4968 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004969 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004970 // TODO: Technically, sending CALLBACK_LOST here is
4971 // incorrect if there is a replacement network currently
4972 // connected that can satisfy nri, which is a request
4973 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004974 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4975 // so this code is only incorrect for a network that loses
4976 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004977 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004978 }
4979 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004980 if (isNewDefault) {
4981 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004982 makeDefault(newNetwork);
4983 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4984 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004985 // Have a new default network, release the transition wakelock in
4986 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004987 }
4988
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004989 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4990 Slog.wtf(TAG, String.format(
4991 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4992 nc, newNetwork.networkCapabilities));
4993 }
4994 if (newNetwork.getCurrentScore() != score) {
4995 Slog.wtf(TAG, String.format(
4996 "BUG: %s changed score during rematch: %d -> %d",
4997 score, newNetwork.getCurrentScore()));
4998 }
4999
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005000 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005001 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5002 // If the network went from background to foreground or vice versa, we need to update
5003 // its foreground state. It is safe to do this after rematching the requests because
5004 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5005 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005006 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005007 } else {
5008 processListenRequests(newNetwork, false);
5009 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005010
Paul Jensencf4c2c62015-07-01 14:16:32 -04005011 // do this after the default net is switched, but
5012 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005013 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005014
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005015 // Linger any networks that are no longer needed. This should be done after sending the
5016 // available callback for newNetwork.
5017 for (NetworkAgentInfo nai : affectedNetworks) {
5018 updateLingerState(nai, now);
5019 }
5020 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5021 // does not need to be done in any particular order.
5022 updateLingerState(newNetwork, now);
5023
Paul Jensencf4c2c62015-07-01 14:16:32 -04005024 if (isNewDefault) {
5025 // Maintain the illusion: since the legacy API only
5026 // understands one network at a time, we must pretend
5027 // that the current default network disconnected before
5028 // the new one connected.
5029 if (oldDefaultNetwork != null) {
5030 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5031 oldDefaultNetwork, true);
5032 }
5033 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5034 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5035 notifyLockdownVpn(newNetwork);
5036 }
5037
Robert Greenwalt7b816022014-04-18 15:25:25 -07005038 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005039 // Notify battery stats service about this network, both the normal
5040 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005041 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005042 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005043 final IBatteryStats bs = BatteryStatsService.getService();
5044 final int type = newNetwork.networkInfo.getType();
5045
5046 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5047 bs.noteNetworkInterfaceType(baseIface, type);
5048 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5049 final String stackedIface = stacked.getInterfaceName();
5050 bs.noteNetworkInterfaceType(stackedIface, type);
5051 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5052 }
5053 } catch (RemoteException ignored) {
5054 }
5055
Robert Greenwalt152ed372014-12-17 17:19:53 -08005056 // This has to happen after the notifyNetworkCallbacks as that tickles each
5057 // ConnectivityManager instance so that legacy requests correctly bind dns
5058 // requests to this network. The legacy users are listening for this bcast
5059 // and will generally do a dns request so they can ensureRouteToHost and if
5060 // they do that before the callbacks happen they'll use the default network.
5061 //
5062 // TODO: Is there still a race here? We send the broadcast
5063 // after sending the callback, but if the app can receive the
5064 // broadcast before the callback, it might still break.
5065 //
5066 // This *does* introduce a race where if the user uses the new api
5067 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5068 // they may get old info. Reverse this after the old startUsing api is removed.
5069 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005070 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5071 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005072 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005073 // legacy type tracker filters out repeat adds
5074 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5075 }
5076 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005077
5078 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5079 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5080 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5081 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5082 if (newNetwork.isVPN()) {
5083 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5084 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005085 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005086 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5087 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005088 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005089 if (nai.getLingerExpiry() > 0) {
5090 // This network has active linger timers and no requests, but is not
5091 // lingering. Linger it.
5092 //
5093 // One way (the only way?) this can happen if this network is unvalidated
5094 // and became unneeded due to another network improving its score to the
5095 // point where this network will no longer be able to satisfy any requests
5096 // even if it validates.
5097 updateLingerState(nai, now);
5098 } else {
5099 if (DBG) log("Reaping " + nai.name());
5100 teardownUnneededNetwork(nai);
5101 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005102 }
5103 }
5104 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 }
5106
Paul Jensen1c7ba022015-06-16 14:27:36 -04005107 /**
5108 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5109 * being disconnected.
5110 * @param changed If only one Network's score or capabilities have been modified since the last
5111 * time this function was called, pass this Network in this argument, otherwise pass
5112 * null.
5113 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5114 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5115 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5116 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5117 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005118 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005119 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005120 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5121 // to avoid the slowness. It is not simply enough to process just "changed", for
5122 // example in the case where "changed"'s score decreases and another network should begin
5123 // satifying a NetworkRequest that "changed" currently satisfies.
5124
5125 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5126 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5127 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005128 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005129 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005130 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005131 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005132 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5133 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5134 // Rematch higher scoring networks first to prevent requests first matching a lower
5135 // scoring network and then a higher scoring network, which could produce multiple
5136 // callbacks and inadvertently unlinger networks.
5137 Arrays.sort(nais);
5138 for (NetworkAgentInfo nai : nais) {
5139 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005140 // Only reap the last time through the loop. Reaping before all rematching
5141 // is complete could incorrectly teardown a network that hasn't yet been
5142 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005143 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005144 : ReapUnvalidatedNetworks.REAP,
5145 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005146 }
5147 }
5148 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005149
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005150 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005151 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005152 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005153 // For now only update icons for default connection.
5154 // TODO: Update WiFi and cellular icons separately. b/17237507
5155 if (!isDefaultNetwork(nai)) return;
5156
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005157 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005158 // Don't repeat publish.
5159 if (newInetCondition == mDefaultInetConditionPublished) return;
5160
5161 mDefaultInetConditionPublished = newInetCondition;
5162 sendInetConditionBroadcast(nai.networkInfo);
5163 }
5164
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005165 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5166 if (mLockdownTracker != null) {
5167 if (nai != null && nai.isVPN()) {
5168 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5169 } else {
5170 mLockdownTracker.onNetworkInfoChanged();
5171 }
5172 }
5173 }
5174
Robert Greenwalt7b816022014-04-18 15:25:25 -07005175 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005176 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005177 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005178 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005179 synchronized (networkAgent) {
5180 oldInfo = networkAgent.networkInfo;
5181 networkAgent.networkInfo = newInfo;
5182 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005183 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005184
5185 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005186 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5187 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5188 notifyIfacesChangedForNetworkStats();
5189 } else if (VDBG) log("ignoring duplicate network state non-change");
5190 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005191 return;
5192 }
5193 if (DBG) {
5194 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5195 (oldInfo == null ? "null" : oldInfo.getState()) +
5196 " to " + state);
5197 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005198
Robin Lee585e2482016-05-01 23:00:00 +01005199 if (!networkAgent.created
5200 && (state == NetworkInfo.State.CONNECTED
5201 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005202
5203 // A network that has just connected has zero requests and is thus a foreground network.
5204 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5205
Robert Greenwalt7b816022014-04-18 15:25:25 -07005206 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005207 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005208 if (networkAgent.isVPN()) {
5209 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005210 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5211 (networkAgent.networkMisc == null ||
5212 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005213 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005214 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005215 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005216 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005217 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005218 loge("Error creating network " + networkAgent.network.netId + ": "
5219 + e.getMessage());
5220 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005221 }
Paul Jenseneec75412014-08-04 12:21:19 -04005222 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005223 }
5224
5225 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5226 networkAgent.everConnected = true;
5227
Robert Greenwalt7b816022014-04-18 15:25:25 -07005228 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005229 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005230
Paul Jensenca8f16a2014-05-09 12:47:55 -04005231 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005232 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005233
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005234 if (networkAgent.isVPN()) {
5235 // Temporarily disable the default proxy (not global).
5236 synchronized (mProxyLock) {
5237 if (!mDefaultProxyDisabled) {
5238 mDefaultProxyDisabled = true;
5239 if (mGlobalProxy == null && mDefaultProxy != null) {
5240 sendProxyBroadcast(null);
5241 }
5242 }
5243 }
5244 // TODO: support proxy per network.
5245 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005246
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005247 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5248 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5249 // capabilities, so it only needs to be done once on initial connect, not every time the
5250 // network's capabilities change. Note that we do this before rematching the network,
5251 // so we could decide to tear it down immediately afterwards. That's fine though - on
5252 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5253 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005254 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005255
Paul Jensen2161a8e2014-09-11 11:00:39 -04005256 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005257 final long now = SystemClock.elapsedRealtime();
5258 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005259
5260 // This has to happen after matching the requests, because callbacks are just requests.
5261 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005262 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005263 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005264 if (networkAgent.isVPN()) {
5265 synchronized (mProxyLock) {
5266 if (mDefaultProxyDisabled) {
5267 mDefaultProxyDisabled = false;
5268 if (mGlobalProxy == null && mDefaultProxy != null) {
5269 sendProxyBroadcast(mDefaultProxy);
5270 }
5271 }
5272 }
5273 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005274 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5275 state == NetworkInfo.State.SUSPENDED) {
5276 // going into or coming out of SUSPEND: rescore and notify
5277 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005278 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005279 }
5280 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5281 ConnectivityManager.CALLBACK_SUSPENDED :
5282 ConnectivityManager.CALLBACK_RESUMED));
5283 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005284 }
5285 }
5286
Robert Greenwaltac96c522014-06-03 16:43:57 -07005287 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005288 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005289 if (score < 0) {
5290 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5291 "). Bumping score to min of 0");
5292 score = 0;
5293 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005294
Paul Jensen2161a8e2014-09-11 11:00:39 -04005295 final int oldScore = nai.getCurrentScore();
5296 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005297
Paul Jensen85cf78e2015-06-25 13:25:07 -04005298 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005299
Paul Jensenc8b9a742014-09-30 15:37:41 -04005300 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005301 }
5302
Erik Klinec75d4fa2017-02-15 19:59:17 +09005303 // Notify only this one new request of the current state. Transfer all the
5304 // current state by calling NetworkCapabilities and LinkProperties callbacks
5305 // so that callers can be guaranteed to have as close to atomicity in state
5306 // transfer as can be supported by this current API.
5307 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005308 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005309 if (nri.mPendingIntent != null) {
5310 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5311 // Attempt no subsequent state pushes where intents are involved.
5312 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005313 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005314
5315 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5316 // Whether a network is currently suspended is also an important
5317 // element of state to be transferred (it would not otherwise be
5318 // delivered by any currently available mechanism).
5319 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5320 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5321 }
5322 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5323 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005324 }
5325
Robert Greenwalt8d482522015-06-24 13:23:42 -07005326 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005327 // The NetworkInfo we actually send out has no bearing on the real
5328 // state of affairs. For example, if the default connection is mobile,
5329 // and a request for HIPRI has just gone away, we need to pretend that
5330 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5331 // the state to DISCONNECTED, even though the network is of type MOBILE
5332 // and is still connected.
5333 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5334 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005335 if (state != DetailedState.DISCONNECTED) {
5336 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005337 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005338 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005339 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005340 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5341 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5342 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5343 if (info.isFailover()) {
5344 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5345 nai.networkInfo.setFailover(false);
5346 }
5347 if (info.getReason() != null) {
5348 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5349 }
5350 if (info.getExtraInfo() != null) {
5351 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5352 }
5353 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005354 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005355 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005356 if (newDefaultAgent != null) {
5357 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5358 newDefaultAgent.networkInfo);
5359 } else {
5360 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5361 }
5362 }
5363 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5364 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005365 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005366 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005367 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005368 }
5369 }
5370 }
5371
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005372 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005373 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005374 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5375 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005376 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5377 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005378 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5379 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005380 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005381 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005382 } else {
5383 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005385 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005386 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005387
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005388 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5389 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5390 }
5391
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005392 private String notifyTypeToName(int notifyType) {
5393 switch (notifyType) {
5394 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5395 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5396 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5397 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5398 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5399 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5400 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5401 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5402 }
5403 return "UNKNOWN";
5404 }
5405
Jeff Sharkey69736342014-12-08 14:50:12 -08005406 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005407 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5408 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005409 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005410 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005411 try {
5412 mStatsService.forceUpdateIfaces();
5413 } catch (Exception ignored) {
5414 }
5415 }
5416
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005417 @Override
5418 public boolean addVpnAddress(String address, int prefixLength) {
5419 throwIfLockdownEnabled();
5420 int user = UserHandle.getUserId(Binder.getCallingUid());
5421 synchronized (mVpns) {
5422 return mVpns.get(user).addAddress(address, prefixLength);
5423 }
5424 }
5425
5426 @Override
5427 public boolean removeVpnAddress(String address, int prefixLength) {
5428 throwIfLockdownEnabled();
5429 int user = UserHandle.getUserId(Binder.getCallingUid());
5430 synchronized (mVpns) {
5431 return mVpns.get(user).removeAddress(address, prefixLength);
5432 }
5433 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005434
5435 @Override
5436 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5437 throwIfLockdownEnabled();
5438 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005439 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005440 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005441 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005442 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005443 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005444 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005445 }
5446 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005447 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005448
5449 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005450 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005451 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005452 }
5453
5454 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005455 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5456 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5457 enforceKeepalivePermission();
5458 mKeepaliveTracker.startNattKeepalive(
5459 getNetworkAgentInfoForNetwork(network),
5460 intervalSeconds, messenger, binder,
5461 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5462 }
5463
5464 @Override
5465 public void stopKeepalive(Network network, int slot) {
5466 mHandler.sendMessage(mHandler.obtainMessage(
5467 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5468 }
5469
5470 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005471 public void factoryReset() {
5472 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005473
5474 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5475 return;
5476 }
5477
Robin Lee3b3dd942015-05-12 18:14:58 +01005478 final int userId = UserHandle.getCallingUserId();
5479
Stuart Scottf1fb3972015-04-02 18:00:02 -07005480 // Turn airplane mode off
5481 setAirplaneMode(false);
5482
Stuart Scotte3e314d2015-04-20 14:07:45 -07005483 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5484 // Untether
5485 for (String tether : getTetheredIfaces()) {
5486 untether(tether);
5487 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005488 }
5489
Stuart Scotte3e314d2015-04-20 14:07:45 -07005490 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005491 // Remove always-on package
5492 synchronized (mVpns) {
5493 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5494 if (alwaysOnPackage != null) {
5495 setAlwaysOnVpnPackage(userId, null, false);
5496 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5497 }
5498 }
5499
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005500 // Turn Always-on VPN off
5501 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5502 final long ident = Binder.clearCallingIdentity();
5503 try {
5504 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5505 mLockdownEnabled = false;
5506 setLockdownTracker(null);
5507 } finally {
5508 Binder.restoreCallingIdentity(ident);
5509 }
5510 }
5511
Stuart Scotte3e314d2015-04-20 14:07:45 -07005512 // Turn VPN off
5513 VpnConfig vpnConfig = getVpnConfig(userId);
5514 if (vpnConfig != null) {
5515 if (vpnConfig.legacy) {
5516 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5517 } else {
5518 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5519 // in the future without user intervention.
5520 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005521
Victor Changb04a5ea2016-05-30 20:36:30 +01005522 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005523 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005524 }
5525 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005526
5527 Settings.Global.putString(mContext.getContentResolver(),
5528 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005529 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005530
5531 @VisibleForTesting
5532 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5533 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5534 return new NetworkMonitor(context, handler, nai, defaultRequest);
5535 }
Erik Kline48f12f22016-04-14 17:30:59 +09005536
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005537 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005538 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5539 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005540 }
5541
5542 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005543 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5544 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5545 }
5546
Hugo Benichicfddd682016-05-31 16:28:06 +09005547 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005548 int newNetid = NETID_UNSET;
5549 int prevNetid = NETID_UNSET;
5550 int[] transports = new int[0];
5551 boolean hadIPv4 = false;
5552 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005553
Hugo Benichi5f16f762016-04-20 12:09:33 +09005554 if (newNai != null) {
5555 newNetid = newNai.network.netId;
5556 transports = newNai.networkCapabilities.getTransportTypes();
5557 }
5558 if (prevNai != null) {
5559 prevNetid = prevNai.network.netId;
5560 final LinkProperties lp = prevNai.linkProperties;
5561 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5562 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5563 }
5564
Hugo Benichicfddd682016-05-31 16:28:06 +09005565 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5566 }
5567
5568 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5569 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571}