blob: 079b6708f67912d460c8b26946cdaf7c468e83e7 [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();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001307 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001308 if (nai != null) {
1309 synchronized (nai) {
1310 return new LinkProperties(nai.linkProperties);
1311 }
1312 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001313 return null;
1314 }
1315
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001316 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001317 if (nai != null) {
1318 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001319 if (nai.networkCapabilities != null) {
1320 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001321 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001322 }
1323 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 return null;
1325 }
1326
1327 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001328 public NetworkCapabilities getNetworkCapabilities(Network network) {
1329 enforceAccessPermission();
1330 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1331 }
1332
1333 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001334 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001335 // Require internal since we're handing out IMSI details
1336 enforceConnectivityInternalPermission();
1337
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001338 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001339 for (Network network : getAllNetworks()) {
1340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1341 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001342 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001343 }
1344 }
1345 return result.toArray(new NetworkState[result.size()]);
1346 }
1347
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001348 @Override
1349 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1350 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001351 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001352 final long token = Binder.clearCallingIdentity();
1353 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1355 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001356 try {
1357 return mPolicyManager.getNetworkQuotaInfo(state);
1358 } catch (RemoteException e) {
1359 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001360 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001361 return null;
1362 } finally {
1363 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001364 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001365 }
1366
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001367 @Override
1368 public boolean isActiveNetworkMetered() {
1369 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001370
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001371 final NetworkInfo info = getActiveNetworkInfo();
1372 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001373 }
1374
Jeff Sharkey216c1812012-08-05 14:29:23 -07001375 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1376 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001377 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001378 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001379 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001380 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001381 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001382
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001383 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 * Ensure that a network route exists to deliver traffic to the specified
1385 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001386 * @param networkType the type of the network over which traffic to the
1387 * specified host is to be routed
1388 * @param hostAddress the IP address of the host to which the route is
1389 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 * @return {@code true} on success, {@code false} on failure
1391 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001392 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001393 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001395 if (mProtectedNetworks.contains(networkType)) {
1396 enforceConnectivityInternalPermission();
1397 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001398
Chad Brubakerc0234532014-02-14 13:24:29 -08001399 InetAddress addr;
1400 try {
1401 addr = InetAddress.getByAddress(hostAddress);
1402 } catch (UnknownHostException e) {
1403 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1404 return false;
1405 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001408 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 return false;
1410 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001411
1412 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1413 if (nai == null) {
1414 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1415 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1416 } else {
1417 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1418 }
1419 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001420 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001421
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001422 DetailedState netState;
1423 synchronized (nai) {
1424 netState = nai.networkInfo.getDetailedState();
1425 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001426
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001427 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001428 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001429 log("requestRouteToHostAddress on down network "
1430 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001431 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001432 }
1433 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001435
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001436 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001437 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001438 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001439 LinkProperties lp;
1440 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001441 synchronized (nai) {
1442 lp = nai.linkProperties;
1443 netId = nai.network.netId;
1444 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001445 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001446 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1447 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001448 } finally {
1449 Binder.restoreCallingIdentity(token);
1450 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001451 }
1452
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001453 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001454 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001456 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001457 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001458 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 if (bestRoute.getGateway().equals(addr)) {
1460 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001461 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001462 } else {
1463 // if we will connect to this through another route, add a direct route
1464 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001465 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 }
1467 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001468 if (DBG) log("Adding legacy route " + bestRoute +
1469 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001470 try {
1471 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1472 } catch (Exception e) {
1473 // never crash - catch them all
1474 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001475 return false;
1476 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001477 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001480 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1481 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001482 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001483 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001485 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001486 }
1487
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001488 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001489 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001490 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001491 if (oldRules == uidRules) return;
1492
Felipe Leme781ba142016-05-09 16:24:48 -07001493 if (uidRules == RULE_NONE) {
1494 mUidRules.delete(uid);
1495 } else {
1496 mUidRules.put(uid, uidRules);
1497 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001498 }
1499
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001500 // TODO: notify UID when it has requested targeted updates
1501 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001502
1503 @Override
1504 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001505 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001506 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001507 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001508 }
1509
1510 synchronized (mRulesLock) {
1511 mMeteredIfaces.clear();
1512 for (String iface : meteredIfaces) {
1513 mMeteredIfaces.add(iface);
1514 }
1515 }
1516 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001517
1518 @Override
1519 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1520 // caller is NPMS, since we only register with them
1521 if (LOGD_RULES) {
1522 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1523 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001524
1525 synchronized (mRulesLock) {
1526 mRestrictBackground = restrictBackground;
1527 }
1528
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001529 if (restrictBackground) {
1530 log("onRestrictBackgroundChanged(true): disabling tethering");
1531 mTethering.untetherAll();
1532 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001533 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001534
1535 @Override
1536 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1537 if (LOGD_RULES) {
1538 // caller is NPMS, since we only register with them
1539 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1540 + whitelisted + ")");
1541 }
1542 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001543 @Override
1544 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1545 if (LOGD_RULES) {
1546 // caller is NPMS, since we only register with them
1547 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1548 + blacklisted + ")");
1549 }
1550 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001551 };
1552
Robin Lee3b3dd942015-05-12 18:14:58 +01001553 /**
1554 * Require that the caller is either in the same user or has appropriate permission to interact
1555 * across users.
1556 *
1557 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1558 */
1559 private void enforceCrossUserPermission(int userId) {
1560 if (userId == UserHandle.getCallingUserId()) {
1561 // Not a cross-user call.
1562 return;
1563 }
1564 mContext.enforceCallingOrSelfPermission(
1565 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1566 "ConnectivityService");
1567 }
1568
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001569 private void enforceInternetPermission() {
1570 mContext.enforceCallingOrSelfPermission(
1571 android.Manifest.permission.INTERNET,
1572 "ConnectivityService");
1573 }
1574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001576 mContext.enforceCallingOrSelfPermission(
1577 android.Manifest.permission.ACCESS_NETWORK_STATE,
1578 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
1581 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001582 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001585 private void enforceTetherAccessPermission() {
1586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.ACCESS_NETWORK_STATE,
1588 "ConnectivityService");
1589 }
1590
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001591 private void enforceConnectivityInternalPermission() {
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1594 "ConnectivityService");
1595 }
1596
Hugo Benichi514da602016-07-19 15:59:27 +09001597 private void enforceConnectivityRestrictedNetworksPermission() {
1598 try {
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1601 "ConnectivityService");
1602 return;
1603 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1604 enforceConnectivityInternalPermission();
1605 }
1606
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001607 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001608 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001609 }
1610
Lorenzo Colitti18660282016-07-04 12:55:44 +09001611 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001612 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001613 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001614 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001615 }
1616
1617 private void sendInetConditionBroadcast(NetworkInfo info) {
1618 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1619 }
1620
Wink Saville628b0852011-08-04 15:01:58 -07001621 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001622 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001623 info = new NetworkInfo(info);
1624 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001625 }
1626
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001627 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001628 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001629 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 if (info.isFailover()) {
1631 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1632 info.setFailover(false);
1633 }
1634 if (info.getReason() != null) {
1635 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1636 }
1637 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001638 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1639 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001641 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001642 return intent;
1643 }
1644
1645 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1646 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1647 }
1648
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001649 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001650 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1651 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1652 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001653 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001654 final long ident = Binder.clearCallingIdentity();
1655 try {
1656 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1657 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1658 } finally {
1659 Binder.restoreCallingIdentity(ident);
1660 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001661 }
1662
Mike Lockwood0f79b542009-08-14 14:18:49 -04001663 private void sendStickyBroadcast(Intent intent) {
1664 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001665 if (!mSystemReady) {
1666 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001667 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001669 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001670 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001671 }
1672
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001673 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001674 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001675 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001676 final NetworkInfo ni = intent.getParcelableExtra(
1677 ConnectivityManager.EXTRA_NETWORK_INFO);
1678 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1679 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1680 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001681 } else {
1682 BroadcastOptions opts = BroadcastOptions.makeBasic();
1683 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1684 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001685 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001686 final IBatteryStats bs = BatteryStatsService.getService();
1687 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001688 bs.noteConnectivityChanged(intent.getIntExtra(
1689 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1690 ni != null ? ni.getState().toString() : "?");
1691 } catch (RemoteException e) {
1692 }
1693 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001694 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001695 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001696 } finally {
1697 Binder.restoreCallingIdentity(ident);
1698 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001699 }
1700 }
1701
1702 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001703 loadGlobalProxy();
1704
Mike Lockwood0f79b542009-08-14 14:18:49 -04001705 synchronized(this) {
1706 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001707 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001708 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001709 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001710 }
1711 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001712 // load the global proxy at startup
1713 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001714
Robin Lee244ce8e2016-01-05 18:03:46 +00001715 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1716 // for user to unlock device too.
1717 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001718
Erik Klineda4bfa82015-04-30 12:58:40 +09001719 // Configure whether mobile data is always on.
1720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1721
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001722 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001723
1724 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001729 *
1730 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001731 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001732 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1734 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001735
1736 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001737 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001738
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 if (networkAgent.networkCapabilities.hasTransport(
1740 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001741 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1742 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001743 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001744 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 } else if (networkAgent.networkCapabilities.hasTransport(
1746 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001747 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1748 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001749 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001751 } else {
1752 // do not track any other networks
1753 timeout = 0;
1754 }
1755
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001757 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001758 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001759 } catch (Exception e) {
1760 // You shall not crash!
1761 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001762 }
1763 }
1764 }
1765
1766 /**
1767 * Remove data activity tracking when network disconnects.
1768 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1770 final String iface = networkAgent.linkProperties.getInterfaceName();
1771 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001772
Robert Greenwalt7b816022014-04-18 15:25:25 -07001773 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1774 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001775 try {
1776 // the call fails silently if no idletimer setup for this interface
1777 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001778 } catch (Exception e) {
1779 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001780 }
1781 }
1782 }
1783
1784 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001785 * Reads the network specific MTU size from reources.
1786 * and set it on it's iface.
1787 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001788 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1789 final String iface = newLp.getInterfaceName();
1790 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001791 if (oldLp == null && mtu == 0) {
1792 // Silently ignore unset MTU value.
1793 return;
1794 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001795 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1796 if (VDBG) log("identical MTU - not setting");
1797 return;
1798 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001799 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001800 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001801 return;
1802 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001803
w1997615afd812014-08-05 15:18:11 -07001804 // Cannot set MTU without interface name
1805 if (TextUtils.isEmpty(iface)) {
1806 loge("Setting MTU size with null iface.");
1807 return;
1808 }
1809
Robert Greenwalt7b816022014-04-18 15:25:25 -07001810 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001811 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001812 mNetd.setMtu(iface, mtu);
1813 } catch (Exception e) {
1814 Slog.e(TAG, "exception in setMtu()" + e);
1815 }
1816 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001817
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001818 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001819 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1820
1821 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001822 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001823 protected MockableSystemProperties getSystemProperties() {
1824 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001825 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001826
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001827 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1828 if (isDefaultNetwork(nai) == false) {
1829 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830 }
1831
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001832 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1833 String[] values = null;
1834 if (tcpBufferSizes != null) {
1835 values = tcpBufferSizes.split(",");
1836 }
1837
1838 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001839 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1841 values = tcpBufferSizes.split(",");
1842 }
1843
1844 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1845
1846 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001847 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001848
1849 final String prefix = "/sys/kernel/ipv4/tcp_";
1850 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1851 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1852 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1853 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1854 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1855 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1856 mCurrentTcpBufferSizes = tcpBufferSizes;
1857 } catch (IOException e) {
1858 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001859 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001860
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001861 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001862 Settings.Global.TCP_DEFAULT_INIT_RWND,
1863 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001864 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1865 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001866 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001867 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001868 }
1869
Mattias Falk8b47b362011-08-23 14:15:13 +02001870 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001871 /*
1872 * Tell the VMs to toss their DNS caches
1873 */
1874 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1875 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001876 /*
1877 * Connectivity events can happen before boot has completed ...
1878 */
1879 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001880 final long ident = Binder.clearCallingIdentity();
1881 try {
1882 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1883 } finally {
1884 Binder.restoreCallingIdentity(ident);
1885 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001886 }
1887
Robert Greenwalt562cc542014-05-15 18:07:26 -07001888 @Override
1889 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001890 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 NETWORK_RESTORE_DELAY_PROP_NAME);
1892 if(restoreDefaultNetworkDelayStr != null &&
1893 restoreDefaultNetworkDelayStr.length() != 0) {
1894 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001895 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 } catch (NumberFormatException e) {
1897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001899 // if the system property isn't set, use the value for the apn type
1900 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1901
1902 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1903 (mNetConfigs[networkType] != null)) {
1904 ret = mNetConfigs[networkType].restoreTime;
1905 }
1906 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001909 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001910 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001911 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001912 }
1913 return false;
1914 }
1915
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001916 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1917 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1918 final long DIAG_TIME_MS = 5000;
1919 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1920 // Start gathering diagnostic information.
1921 netDiags.add(new NetworkDiagnostics(
1922 nai.network,
1923 new LinkProperties(nai.linkProperties), // Must be a copy.
1924 DIAG_TIME_MS));
1925 }
1926
1927 for (NetworkDiagnostics netDiag : netDiags) {
1928 pw.println();
1929 netDiag.waitForMeasurements();
1930 netDiag.dump(pw);
1931 }
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001935 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1936 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001937 if (mContext.checkCallingOrSelfPermission(
1938 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001940 pw.println("Permission Denial: can't dump ConnectivityService " +
1941 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1942 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 return;
1944 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001945
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001946 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001947 dumpNetworkDiagnostics(pw);
1948 return;
1949 }
Erik Kline379747a2015-06-05 17:47:34 +09001950
Lorenzo Colittie3805462015-06-03 11:18:24 +09001951 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001952 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001953 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001954 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001955 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001956 pw.println();
1957
Paul Jensen85cf78e2015-06-25 13:25:07 -04001958 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001959 pw.print("Active default network: ");
1960 if (defaultNai == null) {
1961 pw.println("none");
1962 } else {
1963 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001965 pw.println();
1966
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001967 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001968 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001969 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1970 pw.println(nai.toString());
1971 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001972 pw.println(String.format(
1973 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1974 nai.numForegroundNetworkRequests(),
1975 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1976 nai.numBackgroundNetworkRequests(),
1977 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001978 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001979 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1980 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001981 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001982 pw.decreaseIndent();
1983 pw.println("Lingered:");
1984 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001985 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001986 pw.decreaseIndent();
1987 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001988 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001989 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001991
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001992 pw.println("Metered Interfaces:");
1993 pw.increaseIndent();
1994 for (String value : mMeteredIfaces) {
1995 pw.println(value);
1996 }
1997 pw.decreaseIndent();
1998 pw.println();
1999
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002000 pw.print("Restrict background: ");
2001 pw.println(mRestrictBackground);
2002 pw.println();
2003
Felipe Leme46c4fc32016-05-04 09:21:43 -07002004 pw.println("Status for known UIDs:");
2005 pw.increaseIndent();
2006 final int size = mUidRules.size();
2007 for (int i = 0; i < size; i++) {
2008 final int uid = mUidRules.keyAt(i);
2009 pw.print("UID=");
2010 pw.print(uid);
2011 final int uidRules = mUidRules.get(uid, RULE_NONE);
2012 pw.print(" rules=");
2013 pw.print(uidRulesToString(uidRules));
2014 pw.println();
2015 }
2016 pw.println();
2017 pw.decreaseIndent();
2018
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002019 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002020 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002021 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2022 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002023 }
2024 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002025 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002026
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002027 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002028
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002029 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002030 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002031
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002032 pw.println();
2033 mKeepaliveTracker.dump(pw);
2034
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002035 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002036 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002037
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002038 if (argsContain(args, "--short") == false) {
2039 pw.println();
2040 synchronized (mValidationLogs) {
2041 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002042 for (ValidationLog p : mValidationLogs) {
2043 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002044 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002045 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002046 pw.decreaseIndent();
2047 }
2048 }
Erik Kline7523eb32015-07-09 18:24:03 +09002049
2050 pw.println();
2051 pw.println("mNetworkRequestInfoLogs (most recent first):");
2052 pw.increaseIndent();
2053 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2054 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002055
2056 pw.println();
2057 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2058 pw.increaseIndent();
2059 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2060 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002061
2062 pw.println();
2063 pw.println("NetTransition WakeLock activity (most recent first):");
2064 pw.increaseIndent();
2065 mWakelockLogs.reverseDump(fd, pw, args);
2066 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002070 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002071 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002072 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002073 if (officialNai != null && officialNai.equals(nai)) return true;
2074 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002075 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 " - " + nai);
2077 }
2078 return false;
2079 }
2080
Robert Greenwalt42acef32009-08-12 16:08:25 -07002081 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002082 private class NetworkStateTrackerHandler extends Handler {
2083 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002084 super(looper);
2085 }
2086
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002087 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002089 default:
2090 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002091 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002092 handleAsyncChannelHalfConnect(msg);
2093 break;
2094 }
2095 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2096 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2097 if (nai != null) nai.asyncChannel.disconnect();
2098 break;
2099 }
2100 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2101 handleAsyncChannelDisconnected(msg);
2102 break;
2103 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002104 }
2105 return true;
2106 }
2107
2108 private void maybeHandleNetworkAgentMessage(Message msg) {
2109 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2110 if (nai == null) {
2111 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002112 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002113 }
2114 return;
2115 }
2116
2117 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002119 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2120 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002121 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2122 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002123 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002124 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002125 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002126 break;
2127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 if (VDBG) {
2130 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002131 "; created=" + nai.created +
2132 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002134 LinkProperties oldLp = nai.linkProperties;
2135 synchronized (nai) {
2136 nai.linkProperties = (LinkProperties)msg.obj;
2137 }
Robin Lee585e2482016-05-01 23:00:00 +01002138 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 break;
2140 }
2141 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002142 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 updateNetworkInfo(nai, info);
2144 break;
2145 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002146 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002147 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002148 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002149 break;
2150 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002151 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002152 try {
2153 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002154 } catch (Exception e) {
2155 // Never crash!
2156 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002157 }
2158 break;
2159 }
2160 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 try {
2162 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002163 } catch (Exception e) {
2164 // Never crash!
2165 loge("Exception in removeVpnUidRanges: " + e);
2166 }
2167 break;
2168 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002169 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002170 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2171 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002172 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002173 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002174 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002175 break;
2176 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002177 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002178 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2179 break;
2180 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002181 }
2182 }
2183
2184 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2185 switch (msg.what) {
2186 default:
2187 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002188 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002189 final NetworkAgentInfo nai;
2190 synchronized (mNetworkForNetId) {
2191 nai = mNetworkForNetId.get(msg.arg2);
2192 }
2193 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002194 final boolean valid =
2195 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002196 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002197 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2198 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002199 if (valid != nai.lastValidated) {
2200 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002201 nai.lastValidated = valid;
2202 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002203 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002204 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2205 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002206 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002207 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002208 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002209 Bundle redirectUrlBundle = new Bundle();
2210 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002211 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002212 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002213 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002214 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002215 if (wasValidated && !nai.lastValidated) {
2216 handleNetworkUnvalidated(nai);
2217 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002218 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002219 break;
2220 }
Paul Jensen869868be2014-05-15 10:33:05 -04002221 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002222 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002223 final boolean visible = (msg.arg1 != 0);
2224 final NetworkAgentInfo nai;
2225 synchronized (mNetworkForNetId) {
2226 nai = mNetworkForNetId.get(netId);
2227 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002228 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002229 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002230 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002231 nai.lastCaptivePortalDetected = visible;
2232 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002233 if (nai.lastCaptivePortalDetected &&
2234 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2235 if (DBG) log("Avoiding captive portal network: " + nai.name());
2236 nai.asyncChannel.sendMessage(
2237 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2238 teardownUnneededNetwork(nai);
2239 break;
2240 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002241 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002242 }
2243 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002244 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002245 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002246 if (nai == null) {
2247 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2248 break;
2249 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002250 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002251 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002252 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002253 }
Paul Jensen869868be2014-05-15 10:33:05 -04002254 }
Paul Jensen869868be2014-05-15 10:33:05 -04002255 break;
2256 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002257 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002258 return true;
2259 }
2260
Calvin On1f64f3f2016-10-11 15:10:46 -07002261 private int getCaptivePortalMode() {
2262 return Settings.Global.getInt(mContext.getContentResolver(),
2263 Settings.Global.CAPTIVE_PORTAL_MODE,
2264 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2265 }
2266
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002267 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2268 switch (msg.what) {
2269 default:
2270 return false;
2271 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2272 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2273 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2274 handleLingerComplete(nai);
2275 }
2276 break;
2277 }
2278 }
2279 return true;
2280 }
2281
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002282 @Override
2283 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002284 if (!maybeHandleAsyncChannelMessage(msg) &&
2285 !maybeHandleNetworkMonitorMessage(msg) &&
2286 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002287 maybeHandleNetworkAgentMessage(msg);
2288 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002289 }
2290 }
2291
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002292 private void updateLingerState(NetworkAgentInfo nai, long now) {
2293 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2294 // 2. If the network was lingering and there are now requests, unlinger it.
2295 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2296 // one lingered request, start lingering.
2297 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002298 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002299 if (DBG) log("Unlingering " + nai.name());
2300 nai.unlinger();
2301 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002302 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002304 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002305 nai.linger();
2306 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2307 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2308 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002309 }
2310
Robert Greenwalt7b816022014-04-18 15:25:25 -07002311 private void handleAsyncChannelHalfConnect(Message msg) {
2312 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002313 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2315 if (VDBG) log("NetworkFactory connected");
2316 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002317 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002318 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002319 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002320 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002321 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002322 }
2323 } else {
2324 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002325 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2328 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2329 if (VDBG) log("NetworkAgent connected");
2330 // A network agent has requested a connection. Establish the connection.
2331 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2332 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2333 } else {
2334 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002335 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002337 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002338 synchronized (mNetworkForNetId) {
2339 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002340 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002341 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002342 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002343 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 }
2346 }
2347 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002348
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 private void handleAsyncChannelDisconnected(Message msg) {
2350 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2351 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002352 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002353 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002355 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002356 // TODO - if we move the logic to the network agent (have them disconnect
2357 // because they lost all their requests or because their score isn't good)
2358 // then they would disconnect organically, report their new state and then
2359 // disconnect the channel.
2360 if (nai.networkInfo.isConnected()) {
2361 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2362 null, null);
2363 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 final boolean wasDefault = isDefaultNetwork(nai);
2365 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002366 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002367 // Log default network disconnection before required book-keeping.
2368 // Let rematchAllNetworksAndRequests() below record a new default network event
2369 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2370 // whose timestamps tell how long it takes to recover a default network.
2371 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002372 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002373 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002374 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2375 // by other networks that are already connected. Perhaps that can be done by
2376 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2377 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002378 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002379 mKeepaliveTracker.handleStopAllKeepalives(nai,
2380 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002381 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002382 mNetworkAgentInfos.remove(msg.replyTo);
2383 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002384 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002385 // Remove the NetworkAgent, but don't mark the netId as
2386 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002387 mNetworkForNetId.remove(nai.network.netId);
2388 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002389 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002390 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2391 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002392 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2393 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2394 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 sendUpdatedScoreToFactories(request, 0);
2396 }
2397 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002398 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002399 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002400 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002401 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002402 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002404 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002405 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002406 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002407 if (nai.created) {
2408 // Tell netd to clean up the configuration for this network
2409 // (routing rules, DNS, etc).
2410 // This may be slow as it requires a lot of netd shelling out to ip and
2411 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2412 // after we've rematched networks with requests which should make a potential
2413 // fallback network the default or requested a new network from the
2414 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2415 // long time.
2416 try {
2417 mNetd.removeNetwork(nai.network.netId);
2418 } catch (Exception e) {
2419 loge("Exception removing network: " + e);
2420 }
2421 }
2422 synchronized (mNetworkForNetId) {
2423 mNetIdInUse.delete(nai.network.netId);
2424 }
2425 } else {
2426 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2427 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002428 }
2429 }
2430
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002431 // If this method proves to be too slow then we can maintain a separate
2432 // pendingIntent => NetworkRequestInfo map.
2433 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2434 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2435 Intent intent = pendingIntent.getIntent();
2436 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2437 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2438 if (existingPendingIntent != null &&
2439 existingPendingIntent.getIntent().filterEquals(intent)) {
2440 return entry.getValue();
2441 }
2442 }
2443 return null;
2444 }
2445
2446 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2447 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2448
2449 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2450 if (existingRequest != null) { // remove the existing request.
2451 if (DBG) log("Replacing " + existingRequest.request + " with "
2452 + nri.request + " because their intents matched.");
2453 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2454 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002455 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002456 }
2457
Erik Klineda4bfa82015-04-30 12:58:40 +09002458 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002459 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002460 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002461 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002462 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002463 if (nri.request.networkCapabilities.hasSignalStrength() &&
2464 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2465 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 }
2467 }
2468 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002469 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002470 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002471 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002472 }
2473 }
2474
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002475 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2476 int callingUid) {
2477 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2478 if (nri != null) {
2479 handleReleaseNetworkRequest(nri.request, callingUid);
2480 }
2481 }
2482
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002483 // Determines whether the network is the best (or could become the best, if it validated), for
2484 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2485 // on the value of reason:
2486 //
2487 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2488 // then it should be torn down.
2489 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2490 // then it should be lingered.
2491 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2492 final int numRequests;
2493 switch (reason) {
2494 case TEARDOWN:
2495 numRequests = nai.numRequestNetworkRequests();
2496 break;
2497 case LINGER:
2498 numRequests = nai.numForegroundNetworkRequests();
2499 break;
2500 default:
2501 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2502 return true;
2503 }
2504
2505 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002506 return false;
2507 }
Paul Jensene0988542015-06-25 15:30:08 -04002508 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002509 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2510 // Background requests don't affect lingering.
2511 continue;
2512 }
2513
Paul Jensene0988542015-06-25 15:30:08 -04002514 // If this Network is already the highest scoring Network for a request, or if
2515 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002516 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002517 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002518 // Note that this catches two important cases:
2519 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2520 // is currently satisfying the request. This is desirable when
2521 // cellular ends up validating but WiFi does not.
2522 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002523 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002524 // WiFi ends up validating and out scoring cellular.
2525 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2526 nai.getCurrentScoreAsValidated())) {
2527 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002528 }
2529 }
Paul Jensene0988542015-06-25 15:30:08 -04002530 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002531 }
2532
Erik Klineacdd6392016-07-07 16:50:58 +09002533 private NetworkRequestInfo getNriForAppRequest(
2534 NetworkRequest request, int callingUid, String requestedOperation) {
2535 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2536
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002538 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002539 log(String.format("UID %d attempted to %s for unowned request %s",
2540 callingUid, requestedOperation, nri));
2541 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002542 }
Erik Klineacdd6392016-07-07 16:50:58 +09002543 }
2544
2545 return nri;
2546 }
2547
Erik Kline3841a482015-11-25 12:49:38 +09002548 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2549 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2550 nri.request.requestId) == null) {
2551 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2552 }
2553 }
2554
Erik Klineacdd6392016-07-07 16:50:58 +09002555 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2556 final NetworkRequestInfo nri = getNriForAppRequest(
2557 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002558 if (nri != null) {
2559 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2560 }
2561 }
Erik Klineacdd6392016-07-07 16:50:58 +09002562
Erik Kline3841a482015-11-25 12:49:38 +09002563 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2564 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2565 if (VDBG || (DBG && nri.request.isRequest())) {
2566 log("releasing " + nri.request + " (" + logCallbackType + ")");
2567 }
Erik Klineacdd6392016-07-07 16:50:58 +09002568 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002569 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002570 synchronized (mUidToNetworkRequestCount) {
2571 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2572 if (requests < 1) {
2573 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2574 nri.mUid);
2575 } else if (requests == 1) {
2576 mUidToNetworkRequestCount.removeAt(
2577 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2578 } else {
2579 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2580 }
2581 }
2582 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2583 if (nri.request.isRequest()) {
2584 boolean wasKept = false;
2585 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2586 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002587 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002588 nai.removeRequest(nri.request.requestId);
2589 if (VDBG) {
2590 log(" Removing from current network " + nai.name() +
2591 ", leaving " + nai.numNetworkRequests() + " requests.");
2592 }
2593 // If there are still lingered requests on this network, don't tear it down,
2594 // but resume lingering instead.
2595 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002596 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002597 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2598 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002599 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002600 wasKept = true;
2601 }
2602 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002603 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2604 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002605 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002606 }
Erik Klineacdd6392016-07-07 16:50:58 +09002607 }
2608
2609 // TODO: remove this code once we know that the Slog.wtf is never hit.
2610 //
2611 // Find all networks that are satisfying this request and remove the request
2612 // from their request lists.
2613 // TODO - it's my understanding that for a request there is only a single
2614 // network satisfying it, so this loop is wasteful
2615 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2616 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2617 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2618 otherNai.name() + ", but mNetworkAgentInfos says " +
2619 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002620 }
2621 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002622
Erik Klineacdd6392016-07-07 16:50:58 +09002623 // Maintain the illusion. When this request arrived, we might have pretended
2624 // that a network connected to serve it, even though the network was already
2625 // connected. Now that this request has gone away, we might have to pretend
2626 // that the network disconnected. LegacyTypeTracker will generate that
2627 // phantom disconnect for this type.
2628 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2629 boolean doRemove = true;
2630 if (wasKept) {
2631 // check if any of the remaining requests for this network are for the
2632 // same legacy type - if so, don't remove the nai
2633 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2634 NetworkRequest otherRequest = nai.requestAt(i);
2635 if (otherRequest.legacyType == nri.request.legacyType &&
2636 otherRequest.isRequest()) {
2637 if (DBG) log(" still have other legacy request - leaving");
2638 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002639 }
2640 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002641 }
2642
Erik Klineacdd6392016-07-07 16:50:58 +09002643 if (doRemove) {
2644 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002645 }
2646 }
Erik Klineacdd6392016-07-07 16:50:58 +09002647
2648 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2649 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2650 nri.request);
2651 }
2652 } else {
2653 // listens don't have a singular affectedNetwork. Check all networks to see
2654 // if this listen request applies and remove it.
2655 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2656 nai.removeRequest(nri.request.requestId);
2657 if (nri.request.networkCapabilities.hasSignalStrength() &&
2658 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2659 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2660 }
2661 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002662 }
Erik Kline3841a482015-11-25 12:49:38 +09002663 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002664 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002665
Lorenzo Colitti18660282016-07-04 12:55:44 +09002666 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002667 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2668 enforceConnectivityInternalPermission();
2669 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2670 accept ? 1 : 0, always ? 1: 0, network));
2671 }
2672
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002673 @Override
2674 public void setAvoidUnvalidated(Network network) {
2675 enforceConnectivityInternalPermission();
2676 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2677 }
2678
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002679 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2680 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2681 " accept=" + accept + " always=" + always);
2682
2683 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2684 if (nai == null) {
2685 // Nothing to do.
2686 return;
2687 }
2688
2689 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002690 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002691 return;
2692 }
2693
2694 if (!nai.networkMisc.explicitlySelected) {
2695 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2696 }
2697
2698 if (accept != nai.networkMisc.acceptUnvalidated) {
2699 int oldScore = nai.getCurrentScore();
2700 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002701 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 sendUpdatedScoreToFactories(nai);
2703 }
2704
2705 if (always) {
2706 nai.asyncChannel.sendMessage(
2707 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2708 }
2709
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002710 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002711 // Tell the NetworkAgent to not automatically reconnect to the network.
2712 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2713 // Teardown the nework.
2714 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002715 }
2716
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002717 }
2718
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002719 private void handleSetAvoidUnvalidated(Network network) {
2720 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2721 if (nai == null || nai.lastValidated) {
2722 // Nothing to do. The network either disconnected or revalidated.
2723 return;
2724 }
2725 if (!nai.avoidUnvalidated) {
2726 int oldScore = nai.getCurrentScore();
2727 nai.avoidUnvalidated = true;
2728 rematchAllNetworksAndRequests(nai, oldScore);
2729 sendUpdatedScoreToFactories(nai);
2730 }
2731 }
2732
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002733 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002734 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002735 mHandler.sendMessageDelayed(
2736 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2737 PROMPT_UNVALIDATED_DELAY_MS);
2738 }
2739
Hugo Benichic8e9e122016-09-14 23:23:08 +00002740 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002741 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002742 }
2743
Erik Kline065ab6e2016-10-02 18:02:14 +09002744 private void rematchForAvoidBadWifiUpdate() {
2745 rematchAllNetworksAndRequests(null, 0);
2746 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2747 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2748 sendUpdatedScoreToFactories(nai);
2749 }
2750 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002751 }
2752
Erik Kline065ab6e2016-10-02 18:02:14 +09002753 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002754 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002755 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002756 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002757 if (!configRestrict) {
2758 pw.println("Bad Wi-Fi avoidance: unrestricted");
2759 return;
2760 }
2761
2762 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2763 pw.increaseIndent();
2764 pw.println("Config restrict: " + configRestrict);
2765
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002766 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002767 String description;
2768 // Can't use a switch statement because strings are legal case labels, but null is not.
2769 if ("0".equals(value)) {
2770 description = "get stuck";
2771 } else if (value == null) {
2772 description = "prompt";
2773 } else if ("1".equals(value)) {
2774 description = "avoid";
2775 } else {
2776 description = value + " (?)";
2777 }
2778 pw.println("User setting: " + description);
2779 pw.println("Network overrides:");
2780 pw.increaseIndent();
2781 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2782 if (nai.avoidUnvalidated) {
2783 pw.println(nai.name());
2784 }
2785 }
2786 pw.decreaseIndent();
2787 pw.decreaseIndent();
2788 }
2789
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002790 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2791 final String action;
2792 switch (type) {
2793 case NO_INTERNET:
2794 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2795 break;
2796 case LOST_INTERNET:
2797 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2798 break;
2799 default:
2800 Slog.wtf(TAG, "Unknown notification type " + type);
2801 return;
2802 }
2803
2804 Intent intent = new Intent(action);
2805 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2806 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2807 intent.setClassName("com.android.settings",
2808 "com.android.settings.wifi.WifiNoInternetDialog");
2809
2810 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2811 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2812 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2813 }
2814
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002815 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002816 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002817 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2818
2819 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2820 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002821 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002822 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002823 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2824 return;
2825 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002826 showValidationNotification(nai, NotificationType.NO_INTERNET);
2827 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002828
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002829 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2830 NetworkCapabilities nc = nai.networkCapabilities;
2831 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002832
Erik Kline065ab6e2016-10-02 18:02:14 +09002833 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002834 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002835 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2836 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002837 }
2838
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002839 private class InternalHandler extends Handler {
2840 public InternalHandler(Looper looper) {
2841 super(looper);
2842 }
2843
2844 @Override
2845 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002846 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002847 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002848 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002849 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002850 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002851 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002852 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002853 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002854 break;
2855 }
Jason Monkdecd2952013-10-10 14:02:51 -04002856 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002857 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002858 break;
2859 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002860 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002861 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2862 break;
2863 }
2864 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2865 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002866 break;
2867 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002868 case EVENT_REGISTER_NETWORK_AGENT: {
2869 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2870 break;
2871 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002872 case EVENT_REGISTER_NETWORK_REQUEST:
2873 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002874 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002875 break;
2876 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002877 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2878 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002879 handleRegisterNetworkRequestWithIntent(msg);
2880 break;
2881 }
Erik Kline3841a482015-11-25 12:49:38 +09002882 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2883 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2884 handleTimedOutNetworkRequest(nri);
2885 break;
2886 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002887 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2888 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2889 break;
2890 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002891 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002892 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002893 break;
2894 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002895 case EVENT_SET_ACCEPT_UNVALIDATED: {
2896 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2897 break;
2898 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002899 case EVENT_SET_AVOID_UNVALIDATED: {
2900 handleSetAvoidUnvalidated((Network) msg.obj);
2901 break;
2902 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002903 case EVENT_PROMPT_UNVALIDATED: {
2904 handlePromptUnvalidated((Network) msg.obj);
2905 break;
2906 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002907 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2908 handleMobileDataAlwaysOn();
2909 break;
2910 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002911 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2912 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2913 mKeepaliveTracker.handleStartKeepalive(msg);
2914 break;
2915 }
2916 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2917 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2918 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2919 int slot = msg.arg1;
2920 int reason = msg.arg2;
2921 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2922 break;
2923 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002924 case EVENT_SYSTEM_READY: {
2925 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2926 nai.networkMonitor.systemReady = true;
2927 }
2928 break;
2929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
2931 }
2932 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002933
2934 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002935 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002936 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002937 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002938 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002939 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002940 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002941 } else {
2942 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2943 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002944 }
2945
2946 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002947 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002948 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002949 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002950
2951 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002952 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002953 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002954 } else {
2955 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2956 }
2957 }
2958
2959 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002960 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002961 public int getLastTetherError(String iface) {
2962 enforceTetherAccessPermission();
2963
2964 if (isTetheringSupported()) {
2965 return mTethering.getLastTetherError(iface);
2966 } else {
2967 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2968 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002969 }
2970
2971 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002972 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002973 public String[] getTetherableUsbRegexs() {
2974 enforceTetherAccessPermission();
2975 if (isTetheringSupported()) {
2976 return mTethering.getTetherableUsbRegexs();
2977 } else {
2978 return new String[0];
2979 }
2980 }
2981
Lorenzo Colitti18660282016-07-04 12:55:44 +09002982 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002983 public String[] getTetherableWifiRegexs() {
2984 enforceTetherAccessPermission();
2985 if (isTetheringSupported()) {
2986 return mTethering.getTetherableWifiRegexs();
2987 } else {
2988 return new String[0];
2989 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002990 }
2991
Lorenzo Colitti18660282016-07-04 12:55:44 +09002992 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002993 public String[] getTetherableBluetoothRegexs() {
2994 enforceTetherAccessPermission();
2995 if (isTetheringSupported()) {
2996 return mTethering.getTetherableBluetoothRegexs();
2997 } else {
2998 return new String[0];
2999 }
3000 }
3001
Lorenzo Colitti18660282016-07-04 12:55:44 +09003002 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003003 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003004 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003005 if (isTetheringSupported()) {
3006 return mTethering.setUsbTethering(enable);
3007 } else {
3008 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3009 }
3010 }
3011
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003012 // TODO - move iface listing, queries, etc to new module
3013 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003014 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003015 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003016 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003017 return mTethering.getTetherableIfaces();
3018 }
3019
Lorenzo Colitti18660282016-07-04 12:55:44 +09003020 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003021 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003022 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003023 return mTethering.getTetheredIfaces();
3024 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003025
Lorenzo Colitti18660282016-07-04 12:55:44 +09003026 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003027 public String[] getTetheringErroredIfaces() {
3028 enforceTetherAccessPermission();
3029 return mTethering.getErroredIfaces();
3030 }
3031
Lorenzo Colitti18660282016-07-04 12:55:44 +09003032 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003033 public String[] getTetheredDhcpRanges() {
3034 enforceConnectivityInternalPermission();
3035 return mTethering.getTetheredDhcpRanges();
3036 }
3037
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003038 // if ro.tether.denied = true we default to no tethering
3039 // gservices could set the secure setting to 1 though to enable it on a build where it
3040 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003041 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003042 public boolean isTetheringSupported() {
3043 enforceTetherAccessPermission();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09003044 int defaultVal = (mSystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003045 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003046 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3047 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003048
3049 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3050 boolean adminUser = false;
3051 final long token = Binder.clearCallingIdentity();
3052 try {
3053 adminUser = mUserManager.isAdminUser();
3054 } finally {
3055 Binder.restoreCallingIdentity(token);
3056 }
3057
3058 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09003059 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003060 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003061
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003062 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003063 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003064 ConnectivityManager.enforceTetherChangePermission(mContext);
3065 if (!isTetheringSupported()) {
3066 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3067 return;
3068 }
3069 mTethering.startTethering(type, receiver, showProvisioningUi);
3070 }
3071
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003072 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003073 public void stopTethering(int type) {
3074 ConnectivityManager.enforceTetherChangePermission(mContext);
3075 mTethering.stopTethering(type);
3076 }
3077
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003078 // Called when we lose the default network and have no replacement yet.
3079 // This will automatically be cleared after X seconds or a new default network
3080 // becomes CONNECTED, whichever happens first. The timer is started by the
3081 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003082 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003083 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003084 if (mNetTransitionWakeLock.isHeld()) {
3085 return;
3086 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003087 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003088 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003089 mWakelockLogs.log("ACQUIRE for " + forWhom);
3090 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3091 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003092 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003093
Hugo Benichi4c31b342017-03-30 23:18:10 +09003094 // Called when we gain a new default network to release the network transition wakelock in a
3095 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3096 // message is cancelled.
3097 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003098 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003099 if (!mNetTransitionWakeLock.isHeld()) {
3100 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003101 }
3102 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003103 // Cancel self timeout on wakelock hold.
3104 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3105 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3106 mHandler.sendMessageDelayed(msg, 1000);
3107 }
3108
3109 // Called when either message of ensureNetworkTransitionWakelock or
3110 // scheduleReleaseNetworkTransitionWakelock is processed.
3111 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3112 String event = eventName(eventId);
3113 synchronized (this) {
3114 if (!mNetTransitionWakeLock.isHeld()) {
3115 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3116 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3117 return;
3118 }
3119 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003120 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003121 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003122 }
3123
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003124 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003125 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003126 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003127 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003128 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003129 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003130 }
3131
Lorenzo Colitti18660282016-07-04 12:55:44 +09003132 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003133 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003134 enforceAccessPermission();
3135 enforceInternetPermission();
3136
Paul Jensenbfd17b72015-04-07 12:43:13 -04003137 NetworkAgentInfo nai;
3138 if (network == null) {
3139 nai = getDefaultNetwork();
3140 } else {
3141 nai = getNetworkAgentInfoForNetwork(network);
3142 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003143 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3144 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3145 return;
3146 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003147 // Revalidate if the app report does not match our current validated state.
3148 if (hasConnectivity == nai.lastValidated) return;
3149 final int uid = Binder.getCallingUid();
3150 if (DBG) {
3151 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3152 ") by " + uid);
3153 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003154 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003155 // Validating a network that has not yet connected could result in a call to
3156 // rematchNetworkAndRequests() which is not meant to work on such networks.
3157 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003158
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003159 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003160
3161 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3162 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003163 }
3164
Paul Jensencee9b512015-05-06 07:32:40 -04003165 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003166 // this information is already available as a world read/writable jvm property
3167 // so this API change wouldn't have a benifit. It also breaks the passing
3168 // of proxy info to all the JVMs.
3169 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003170 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003171 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003172 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3173 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003174 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003175 }
3176
Lorenzo Colitti18660282016-07-04 12:55:44 +09003177 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003178 public ProxyInfo getProxyForNetwork(Network network) {
3179 if (network == null) return getDefaultProxy();
3180 final ProxyInfo globalProxy = getGlobalProxy();
3181 if (globalProxy != null) return globalProxy;
3182 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3183 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3184 // caller may not have.
3185 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3186 if (nai == null) return null;
3187 synchronized (nai) {
3188 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3189 if (proxyInfo == null) return null;
3190 return new ProxyInfo(proxyInfo);
3191 }
3192 }
3193
Paul Jensene0bef712014-12-10 15:12:18 -05003194 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3195 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3196 // proxy is null then there is no proxy in place).
3197 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3198 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3199 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3200 proxy = null;
3201 }
3202 return proxy;
3203 }
3204
3205 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3206 // better for determining if a new proxy broadcast is necessary:
3207 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3208 // avoid unnecessary broadcasts.
3209 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3210 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3211 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3212 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3213 // all set.
3214 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3215 a = canonicalizeProxyInfo(a);
3216 b = canonicalizeProxyInfo(b);
3217 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3218 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3219 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3220 }
3221
Jason Monk207900c2014-04-25 15:00:09 -04003222 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003223 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003224
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003225 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003226 if (proxyProperties == mGlobalProxy) return;
3227 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3228 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3229
3230 String host = "";
3231 int port = 0;
3232 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003233 String pacFileUrl = "";
3234 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003235 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003236 if (!proxyProperties.isValid()) {
3237 if (DBG)
3238 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3239 return;
3240 }
Jason Monk207900c2014-04-25 15:00:09 -04003241 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003242 host = mGlobalProxy.getHost();
3243 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003244 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003245 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003246 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003247 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 } else {
3249 mGlobalProxy = null;
3250 }
3251 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003252 final long token = Binder.clearCallingIdentity();
3253 try {
3254 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3255 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3256 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3257 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003258 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003259 } finally {
3260 Binder.restoreCallingIdentity(token);
3261 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003262
Jason Monkcf0f97a2014-10-02 15:39:38 -04003263 if (mGlobalProxy == null) {
3264 proxyProperties = mDefaultProxy;
3265 }
3266 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 }
3269
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003270 private void loadGlobalProxy() {
3271 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003272 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3273 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3274 String exclList = Settings.Global.getString(res,
3275 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003276 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3277 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003278 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003279 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003280 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003281 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003282 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003283 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003284 if (!proxyProperties.isValid()) {
3285 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3286 return;
3287 }
3288
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003290 mGlobalProxy = proxyProperties;
3291 }
3292 }
3293 }
3294
Jason Monk207900c2014-04-25 15:00:09 -04003295 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003296 // this information is already available as a world read/writable jvm property
3297 // so this API change wouldn't have a benifit. It also breaks the passing
3298 // of proxy info to all the JVMs.
3299 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003300 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003301 return mGlobalProxy;
3302 }
3303 }
3304
Jason Monk207900c2014-04-25 15:00:09 -04003305 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003306 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003307 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003308 proxy = null;
3309 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003310 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003312 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003313 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003314 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3315 return;
3316 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003317
3318 // This call could be coming from the PacManager, containing the port of the local
3319 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3320 // global (to get the correct local port), and send a broadcast.
3321 // TODO: Switch PacManager to have its own message to send back rather than
3322 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003323 if ((mGlobalProxy != null) && (proxy != null)
3324 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003325 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3326 mGlobalProxy = proxy;
3327 sendProxyBroadcast(mGlobalProxy);
3328 return;
3329 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003330 mDefaultProxy = proxy;
3331
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003332 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003333 if (!mDefaultProxyDisabled) {
3334 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 }
3336 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003337 }
3338
Paul Jensene0bef712014-12-10 15:12:18 -05003339 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3340 // This method gets called when any network changes proxy, but the broadcast only ever contains
3341 // the default proxy (even if it hasn't changed).
3342 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3343 // world where an app might be bound to a non-default network.
3344 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3345 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3346 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3347
3348 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3349 sendProxyBroadcast(getDefaultProxy());
3350 }
3351 }
3352
Robert Greenwalt434203a2010-10-11 16:00:27 -07003353 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003354 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3355 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 if (!TextUtils.isEmpty(proxy)) {
3357 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003358 if (data.length == 0) {
3359 return;
3360 }
3361
Robert Greenwalt434203a2010-10-11 16:00:27 -07003362 String proxyHost = data[0];
3363 int proxyPort = 8080;
3364 if (data.length > 1) {
3365 try {
3366 proxyPort = Integer.parseInt(data[1]);
3367 } catch (NumberFormatException e) {
3368 return;
3369 }
3370 }
Jason Monk207900c2014-04-25 15:00:09 -04003371 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003372 setGlobalProxy(p);
3373 }
3374 }
3375
Jason Monk207900c2014-04-25 15:00:09 -04003376 private void sendProxyBroadcast(ProxyInfo proxy) {
3377 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003378 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003379 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003380 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003381 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3382 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003384 final long ident = Binder.clearCallingIdentity();
3385 try {
3386 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3387 } finally {
3388 Binder.restoreCallingIdentity(ident);
3389 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003390 }
3391
3392 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003393 final private HashMap<Uri, Integer> mUriEventMap;
3394 final private Context mContext;
3395 final private Handler mHandler;
3396
3397 SettingsObserver(Context context, Handler handler) {
3398 super(null);
3399 mUriEventMap = new HashMap<Uri, Integer>();
3400 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 }
3403
Erik Klineda4bfa82015-04-30 12:58:40 +09003404 void observe(Uri uri, int what) {
3405 mUriEventMap.put(uri, what);
3406 final ContentResolver resolver = mContext.getContentResolver();
3407 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 }
3409
3410 @Override
3411 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003412 Slog.wtf(TAG, "Should never be reached.");
3413 }
3414
3415 @Override
3416 public void onChange(boolean selfChange, Uri uri) {
3417 final Integer what = mUriEventMap.get(uri);
3418 if (what != null) {
3419 mHandler.obtainMessage(what.intValue()).sendToTarget();
3420 } else {
3421 loge("No matching event to send for URI=" + uri);
3422 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003423 }
3424 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003425
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003426 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003427 Slog.d(TAG, s);
3428 }
3429
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003430 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003431 Slog.e(TAG, s);
3432 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003433
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003434 private static <T> T checkNotNull(T value, String message) {
3435 if (value == null) {
3436 throw new NullPointerException(message);
3437 }
3438 return value;
3439 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003440
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003441 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003442 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003443 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3444 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3445 *
3446 * @param oldPackage Package name of the application which currently controls VPN, which will
3447 * be replaced. If there is no such application, this should should either be
3448 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3449 * @param newPackage Package name of the application which should gain control of VPN, or
3450 * {@code null} to disable.
3451 * @param userId User for whom to prepare the new VPN.
3452 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003453 * @hide
3454 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003455 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003456 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3457 int userId) {
3458 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003459 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003460
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003461 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003462 Vpn vpn = mVpns.get(userId);
3463 if (vpn != null) {
3464 return vpn.prepare(oldPackage, newPackage);
3465 } else {
3466 return false;
3467 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003468 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003469 }
3470
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003471 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003472 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3473 * This method is used by system-privileged apps.
3474 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3475 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3476 *
3477 * @param packageName The package for which authorization state should change.
3478 * @param userId User for whom {@code packageName} is installed.
3479 * @param authorized {@code true} if this app should be able to start a VPN connection without
3480 * explicit user approval, {@code false} if not.
3481 *
Jeff Davidson05542602014-08-11 14:07:27 -07003482 * @hide
3483 */
3484 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003485 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3486 enforceCrossUserPermission(userId);
3487
Jeff Davidson05542602014-08-11 14:07:27 -07003488 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003489 Vpn vpn = mVpns.get(userId);
3490 if (vpn != null) {
3491 vpn.setPackageAuthorization(packageName, authorized);
3492 }
Jeff Davidson05542602014-08-11 14:07:27 -07003493 }
3494 }
3495
3496 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003497 * Configure a TUN interface and return its file descriptor. Parameters
3498 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003499 * and not available in ConnectivityManager. Permissions are checked in
3500 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003501 * @hide
3502 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003503 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003504 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003505 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003506 int user = UserHandle.getUserId(Binder.getCallingUid());
3507 synchronized(mVpns) {
3508 return mVpns.get(user).establish(config);
3509 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003510 }
3511
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003512 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003513 * Start legacy VPN, controlling native daemons as needed. Creates a
3514 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003515 */
3516 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003517 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003518 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003519 final LinkProperties egress = getActiveLinkProperties();
3520 if (egress == null) {
3521 throw new IllegalStateException("Missing active network connection");
3522 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003523 int user = UserHandle.getUserId(Binder.getCallingUid());
3524 synchronized(mVpns) {
3525 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3526 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003527 }
3528
3529 /**
3530 * Return the information of the ongoing legacy VPN. This method is used
3531 * by VpnSettings and not available in ConnectivityManager. Permissions
3532 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003533 */
3534 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003535 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3536 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003537
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003538 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003539 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003540 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003541 }
3542
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003543 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003544 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3545 * and not available in ConnectivityManager.
3546 */
3547 @Override
3548 public VpnInfo[] getAllVpnInfo() {
3549 enforceConnectivityInternalPermission();
3550 if (mLockdownEnabled) {
3551 return new VpnInfo[0];
3552 }
3553
3554 synchronized(mVpns) {
3555 List<VpnInfo> infoList = new ArrayList<>();
3556 for (int i = 0; i < mVpns.size(); i++) {
3557 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3558 if (info != null) {
3559 infoList.add(info);
3560 }
3561 }
3562 return infoList.toArray(new VpnInfo[infoList.size()]);
3563 }
3564 }
3565
3566 /**
3567 * @return VPN information for accounting, or null if we can't retrieve all required
3568 * information, e.g primary underlying iface.
3569 */
3570 @Nullable
3571 private VpnInfo createVpnInfo(Vpn vpn) {
3572 VpnInfo info = vpn.getVpnInfo();
3573 if (info == null) {
3574 return null;
3575 }
3576 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3577 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3578 // the underlyingNetworks list.
3579 if (underlyingNetworks == null) {
3580 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3581 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3582 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3583 }
3584 } else if (underlyingNetworks.length > 0) {
3585 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3586 if (linkProperties != null) {
3587 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3588 }
3589 }
3590 return info.primaryUnderlyingIface == null ? null : info;
3591 }
3592
3593 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003594 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3595 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003596 * Permissions are checked in Vpn class.
3597 * @hide
3598 */
3599 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003600 public VpnConfig getVpnConfig(int userId) {
3601 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003602 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003603 Vpn vpn = mVpns.get(userId);
3604 if (vpn != null) {
3605 return vpn.getVpnConfig();
3606 } else {
3607 return null;
3608 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003609 }
3610 }
3611
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003612 @Override
3613 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003614 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3615 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3616 return false;
3617 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003618
3619 // Tear down existing lockdown if profile was removed
3620 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3621 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003622 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3623 if (profileTag == null) {
3624 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3625 return false;
3626 }
3627 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003628 final VpnProfile profile = VpnProfile.decode(
3629 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003630 if (profile == null) {
3631 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3632 setLockdownTracker(null);
3633 return true;
3634 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003635 int user = UserHandle.getUserId(Binder.getCallingUid());
3636 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003637 Vpn vpn = mVpns.get(user);
3638 if (vpn == null) {
3639 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3640 return false;
3641 }
3642 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003644 } else {
3645 setLockdownTracker(null);
3646 }
3647
3648 return true;
3649 }
3650
3651 /**
3652 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3653 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3654 */
3655 private void setLockdownTracker(LockdownVpnTracker tracker) {
3656 // Shutdown any existing tracker
3657 final LockdownVpnTracker existing = mLockdownTracker;
3658 mLockdownTracker = null;
3659 if (existing != null) {
3660 existing.shutdown();
3661 }
3662
3663 try {
3664 if (tracker != null) {
3665 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003666 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003667 mLockdownTracker = tracker;
3668 mLockdownTracker.init();
3669 } else {
3670 mNetd.setFirewallEnabled(false);
3671 }
3672 } catch (RemoteException e) {
3673 // ignored; NMS lives inside system_server
3674 }
3675 }
3676
3677 private void throwIfLockdownEnabled() {
3678 if (mLockdownEnabled) {
3679 throw new IllegalStateException("Unavailable in lockdown mode");
3680 }
3681 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003682
Robin Lee244ce8e2016-01-05 18:03:46 +00003683 /**
Robin Lee17e61832016-05-09 13:46:28 +01003684 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3685 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003686 *
Robin Lee17e61832016-05-09 13:46:28 +01003687 * @return {@code true} if the service was started, the service was already connected, or there
3688 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003689 */
Robin Lee17e61832016-05-09 13:46:28 +01003690 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003691 synchronized (mVpns) {
3692 Vpn vpn = mVpns.get(userId);
3693 if (vpn == null) {
3694 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3695 // exists already.
3696 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3697 return false;
3698 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003699
Robin Lee812800c2016-05-13 15:38:08 +01003700 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003701 }
3702 }
3703
3704 @Override
Robin Leedc679712016-05-03 13:23:03 +01003705 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003706 enforceConnectivityInternalPermission();
3707 enforceCrossUserPermission(userId);
3708
3709 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3710 if (LockdownVpnTracker.isEnabled()) {
3711 return false;
3712 }
3713
Robin Lee244ce8e2016-01-05 18:03:46 +00003714 synchronized (mVpns) {
3715 Vpn vpn = mVpns.get(userId);
3716 if (vpn == null) {
3717 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3718 return false;
3719 }
Robin Lee17e61832016-05-09 13:46:28 +01003720 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003721 return false;
3722 }
Robin Lee17e61832016-05-09 13:46:28 +01003723 if (!startAlwaysOnVpn(userId)) {
3724 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003725 return false;
3726 }
3727 }
3728 return true;
3729 }
3730
3731 @Override
3732 public String getAlwaysOnVpnPackage(int userId) {
3733 enforceConnectivityInternalPermission();
3734 enforceCrossUserPermission(userId);
3735
3736 synchronized (mVpns) {
3737 Vpn vpn = mVpns.get(userId);
3738 if (vpn == null) {
3739 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3740 return null;
3741 }
3742 return vpn.getAlwaysOnPackage();
3743 }
3744 }
3745
Wink Savilleab9321d2013-06-29 21:10:57 -07003746 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003747 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003748 // TODO: Remove? Any reason to trigger a provisioning check?
3749 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003750 }
3751
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003752 /** Location to an updatable file listing carrier provisioning urls.
3753 * An example:
3754 *
3755 * <?xml version="1.0" encoding="utf-8"?>
3756 * <provisioningUrls>
3757 * <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 -07003758 * </provisioningUrls>
3759 */
3760 private static final String PROVISIONING_URL_PATH =
3761 "/data/misc/radio/provisioning_urls.xml";
3762 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003763
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003764 /** XML tag for root element. */
3765 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3766 /** XML tag for individual url */
3767 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003768 /** XML attribute for mcc */
3769 private static final String ATTR_MCC = "mcc";
3770 /** XML attribute for mnc */
3771 private static final String ATTR_MNC = "mnc";
3772
Paul Jensen434dde82015-06-11 09:43:30 -04003773 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003774 FileReader fileReader = null;
3775 XmlPullParser parser = null;
3776 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003777
3778 try {
3779 fileReader = new FileReader(mProvisioningUrlFile);
3780 parser = Xml.newPullParser();
3781 parser.setInput(fileReader);
3782 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3783
3784 while (true) {
3785 XmlUtils.nextElement(parser);
3786
3787 String element = parser.getName();
3788 if (element == null) break;
3789
Paul Jensen434dde82015-06-11 09:43:30 -04003790 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003791 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3792 try {
3793 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3794 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3795 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3796 parser.next();
3797 if (parser.getEventType() == XmlPullParser.TEXT) {
3798 return parser.getText();
3799 }
3800 }
3801 }
3802 } catch (NumberFormatException e) {
3803 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3804 }
3805 }
3806 }
3807 return null;
3808 } catch (FileNotFoundException e) {
3809 loge("Carrier Provisioning Urls file not found");
3810 } catch (XmlPullParserException e) {
3811 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3812 } catch (IOException e) {
3813 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3814 } finally {
3815 if (fileReader != null) {
3816 try {
3817 fileReader.close();
3818 } catch (IOException e) {}
3819 }
3820 }
3821 return null;
3822 }
3823
Wink Saville42d4f082013-07-20 20:31:59 -07003824 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003825 public String getMobileProvisioningUrl() {
3826 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003827 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003828 if (TextUtils.isEmpty(url)) {
3829 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003830 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003831 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003832 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003833 }
Wink Saville8cf35602013-07-10 23:00:07 -07003834 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003835 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003836 String phoneNumber = mTelephonyManager.getLine1Number();
3837 if (TextUtils.isEmpty(phoneNumber)) {
3838 phoneNumber = "0000000000";
3839 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003840 url = String.format(url,
3841 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3842 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003843 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003844 }
3845
Wink Savilleab9321d2013-06-29 21:10:57 -07003846 return url;
3847 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003848
Wink Saville948282b2013-08-29 08:55:16 -07003849 @Override
3850 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003851 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003852 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003853 final long ident = Binder.clearCallingIdentity();
3854 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003855 // Concatenate the range of types onto the range of NetIDs.
3856 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3857 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003858 } finally {
3859 Binder.restoreCallingIdentity(ident);
3860 }
Wink Saville948282b2013-08-29 08:55:16 -07003861 }
Wink Saville7788c612013-08-29 14:57:08 -07003862
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003863 @Override
3864 public void setAirplaneMode(boolean enable) {
3865 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003866 final long ident = Binder.clearCallingIdentity();
3867 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003868 final ContentResolver cr = mContext.getContentResolver();
3869 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3870 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3871 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003872 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003873 } finally {
3874 Binder.restoreCallingIdentity(ident);
3875 }
3876 }
3877
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003878 private void onUserStart(int userId) {
3879 synchronized(mVpns) {
3880 Vpn userVpn = mVpns.get(userId);
3881 if (userVpn != null) {
3882 loge("Starting user already has a VPN");
3883 return;
3884 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003885 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003886 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003888 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3889 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003890 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891 }
3892
3893 private void onUserStop(int userId) {
3894 synchronized(mVpns) {
3895 Vpn userVpn = mVpns.get(userId);
3896 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003897 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003898 return;
3899 }
Robin Lee17e61832016-05-09 13:46:28 +01003900 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003901 mVpns.delete(userId);
3902 }
3903 }
3904
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003905 private void onUserAdded(int userId) {
3906 synchronized(mVpns) {
3907 final int vpnsSize = mVpns.size();
3908 for (int i = 0; i < vpnsSize; i++) {
3909 Vpn vpn = mVpns.valueAt(i);
3910 vpn.onUserAdded(userId);
3911 }
3912 }
3913 }
3914
3915 private void onUserRemoved(int userId) {
3916 synchronized(mVpns) {
3917 final int vpnsSize = mVpns.size();
3918 for (int i = 0; i < vpnsSize; i++) {
3919 Vpn vpn = mVpns.valueAt(i);
3920 vpn.onUserRemoved(userId);
3921 }
3922 }
3923 }
3924
Robin Lee89e7a692016-02-29 14:38:17 +00003925 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003926 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3927 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3928 updateLockdownVpn();
3929 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003930 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003931 }
3932 }
3933
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003934 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3935 @Override
3936 public void onReceive(Context context, Intent intent) {
3937 final String action = intent.getAction();
3938 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3939 if (userId == UserHandle.USER_NULL) return;
3940
Robin Lee323f29d2016-05-04 16:38:06 +01003941 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003942 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003943 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003944 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003945 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3946 onUserAdded(userId);
3947 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3948 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003949 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3950 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003951 }
3952 }
3953 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003954
Robin Lee95204e02017-01-27 11:59:22 +00003955 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3956 @Override
3957 public void onReceive(Context context, Intent intent) {
3958 // Try creating lockdown tracker, since user present usually means
3959 // unlocked keystore.
3960 updateLockdownVpn();
3961 mContext.unregisterReceiver(this);
3962 }
3963 };
3964
Robert Greenwalta67be032014-05-16 15:49:14 -07003965 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3966 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003967 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3968 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003969
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003970 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3971 // Map from UID to number of NetworkRequests that UID has filed.
3972 @GuardedBy("mUidToNetworkRequestCount")
3973 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3974
Robert Greenwalta67be032014-05-16 15:49:14 -07003975 private static class NetworkFactoryInfo {
3976 public final String name;
3977 public final Messenger messenger;
3978 public final AsyncChannel asyncChannel;
3979
3980 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3981 this.name = name;
3982 this.messenger = messenger;
3983 this.asyncChannel = asyncChannel;
3984 }
3985 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003987 private void ensureNetworkRequestHasType(NetworkRequest request) {
3988 if (request.type == NetworkRequest.Type.NONE) {
3989 throw new IllegalArgumentException(
3990 "All NetworkRequests in ConnectivityService must have a type");
3991 }
3992 }
3993
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003994 /**
3995 * Tracks info about the requester.
3996 * Also used to notice when the calling process dies so we can self-expire
3997 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003998 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004000 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004001 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004002 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004003 final int mPid;
4004 final int mUid;
4005 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004006
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004007 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004008 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004009 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004010 mPendingIntent = pi;
4011 messenger = null;
4012 mBinder = null;
4013 mPid = getCallingPid();
4014 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004015 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004016 }
4017
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004018 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 super();
4020 messenger = m;
4021 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004022 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 mBinder = binder;
4024 mPid = getCallingPid();
4025 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004027 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004028
4029 try {
4030 mBinder.linkToDeath(this, 0);
4031 } catch (RemoteException e) {
4032 binderDied();
4033 }
4034 }
4035
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004036 private void enforceRequestCountLimit() {
4037 synchronized (mUidToNetworkRequestCount) {
4038 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4039 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4040 throw new IllegalArgumentException("Too many NetworkRequests filed");
4041 }
4042 mUidToNetworkRequestCount.put(mUid, networkRequests);
4043 }
4044 }
4045
Robert Greenwalt9258c642014-03-26 16:47:06 -07004046 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 if (mBinder != null) {
4048 mBinder.unlinkToDeath(this, 0);
4049 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004050 }
4051
4052 public void binderDied() {
4053 log("ConnectivityService NetworkRequestInfo binderDied(" +
4054 request + ", " + mBinder + ")");
4055 releaseNetworkRequest(request);
4056 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004057
4058 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004059 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004060 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004061 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004062 }
4063
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004064 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4065 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4066 if (badCapability != null) {
4067 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004068 }
4069 }
4070
Erik Kline9d598e12015-07-13 16:37:51 +09004071 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004072 final SortedSet<Integer> thresholds = new TreeSet();
4073 synchronized (nai) {
4074 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4075 if (nri.request.networkCapabilities.hasSignalStrength() &&
4076 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4077 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4078 }
4079 }
4080 }
Erik Kline9d598e12015-07-13 16:37:51 +09004081 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004082 }
4083
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004084 private void updateSignalStrengthThresholds(
4085 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4086 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004087 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004088 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4089
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004090 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004091 String detail;
4092 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4093 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4094 } else {
4095 detail = reason;
4096 }
4097 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4098 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4099 }
4100
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004101 nai.asyncChannel.sendMessage(
4102 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004103 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004104 }
4105
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 @Override
4107 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004108 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004109 final NetworkRequest.Type type = (networkCapabilities == null)
4110 ? NetworkRequest.Type.TRACK_DEFAULT
4111 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004112 // If the requested networkCapabilities is null, take them instead from
4113 // the default network request. This allows callers to keep track of
4114 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004115 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004116 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4117 enforceAccessPermission();
4118 } else {
4119 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4120 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004121 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4122 // of the app when the request is filed, but we never change the request if the app
4123 // changes network state. http://b/29964605
4124 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004125 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004126 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004127
Etan Cohenba07c8c2017-02-05 10:42:27 -08004128 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004129 throw new IllegalArgumentException("Bad timeout specified");
4130 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004131
Etan Cohena7434272017-04-03 12:17:51 -07004132 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4133 networkCapabilities.getNetworkSpecifier());
Etan Cohenddb9ef02015-11-18 10:56:15 -08004134
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004135 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004136 nextNetworkRequestId(), type);
4137 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004138 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139
4140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004141 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004143 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 }
4145 return networkRequest;
4146 }
4147
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004149 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004150 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004151 } else {
4152 enforceChangePermission();
4153 }
4154 }
4155
fenglub15e72b2015-03-20 11:29:56 -07004156 @Override
fengludb571472015-04-21 17:12:05 -07004157 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004158 enforceAccessPermission();
4159 NetworkAgentInfo nai = null;
4160 if (network == null) {
4161 return false;
4162 }
4163 synchronized (mNetworkForNetId) {
4164 nai = mNetworkForNetId.get(network.netId);
4165 }
4166 if (nai != null) {
4167 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4168 return true;
4169 }
4170 return false;
4171 }
4172
Felipe Lemeee27cab2016-06-20 16:36:29 -07004173 private boolean isSystem(int uid) {
4174 return uid < Process.FIRST_APPLICATION_UID;
4175 }
fenglub15e72b2015-03-20 11:29:56 -07004176
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004177 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004178 final int uid = Binder.getCallingUid();
4179 if (isSystem(uid)) {
4180 return;
4181 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004182 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004183 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004184 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004185 synchronized(mRulesLock) {
4186 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4187 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004188 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4189 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004191 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004192 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 }
4194 }
4195 }
4196
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 @Override
4198 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4199 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 checkNotNull(operation, "PendingIntent cannot be null.");
4201 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4202 enforceNetworkRequestPermissions(networkCapabilities);
4203 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004204 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004205
Etan Cohena7434272017-04-03 12:17:51 -07004206 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4207 networkCapabilities.getNetworkSpecifier());
4208
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004210 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4211 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004212 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4214 nri));
4215 return networkRequest;
4216 }
4217
Jeremy Joslin79294842014-12-03 17:15:28 -08004218 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4219 mHandler.sendMessageDelayed(
4220 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4221 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4222 }
4223
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004224 @Override
4225 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004226 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4228 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 }
4230
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004231 // In order to implement the compatibility measure for pre-M apps that call
4232 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4233 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4234 // This ensures it has permission to do so.
4235 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4236 if (nc == null) {
4237 return false;
4238 }
4239 int[] transportTypes = nc.getTransportTypes();
4240 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4241 return false;
4242 }
4243 try {
4244 mContext.enforceCallingOrSelfPermission(
4245 android.Manifest.permission.ACCESS_WIFI_STATE,
4246 "ConnectivityService");
4247 } catch (SecurityException e) {
4248 return false;
4249 }
4250 return true;
4251 }
4252
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 @Override
4254 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4255 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004256 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4257 enforceAccessPermission();
4258 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004260 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4261 if (!ConnectivityManager.checkChangePermission(mContext)) {
4262 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4263 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4264 // onLost and onAvailable callbacks when networks move in and out of the background.
4265 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4266 // can't request networks.
4267 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4268 }
4269
Etan Cohena7434272017-04-03 12:17:51 -07004270 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4271 networkCapabilities.getNetworkSpecifier());
4272
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004273 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004274 NetworkRequest.Type.LISTEN);
4275 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004276 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277
4278 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4279 return networkRequest;
4280 }
4281
4282 @Override
4283 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4284 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004285 checkNotNull(operation, "PendingIntent cannot be null.");
4286 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4287 enforceAccessPermission();
4288 }
4289
Etan Cohena7434272017-04-03 12:17:51 -07004290 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4291 networkCapabilities.getNetworkSpecifier());
4292
Erik Kline7523eb32015-07-09 18:24:03 +09004293 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004294 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4295 NetworkRequest.Type.LISTEN);
4296 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004297 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004298
4299 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004300 }
4301
Erik Klineacdd6392016-07-07 16:50:58 +09004302 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004303 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004304 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004305 mHandler.sendMessage(mHandler.obtainMessage(
4306 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307 }
4308
4309 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004310 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004311 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004312 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4313 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004314 }
4315
Robert Greenwalta67be032014-05-16 15:49:14 -07004316 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004317 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004318 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4319 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4320 }
4321
4322 @Override
4323 public void unregisterNetworkFactory(Messenger messenger) {
4324 enforceConnectivityInternalPermission();
4325 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4326 }
4327
4328 private void handleUnregisterNetworkFactory(Messenger messenger) {
4329 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4330 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004331 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004332 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004333 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004334 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004335 }
4336
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 /**
4338 * NetworkAgentInfo supporting a request by requestId.
4339 * These have already been vetted (their Capabilities satisfy the request)
4340 * and the are the highest scored network available.
4341 * the are keyed off the Requests requestId.
4342 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004343 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004344 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4345 new SparseArray<NetworkAgentInfo>();
4346
Paul Jensen31a94f42015-02-13 14:18:39 -05004347 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4348 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004349 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4350 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004351 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4352 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4353 // there may not be a strict 1:1 correlation between the two.
4354 @GuardedBy("mNetworkForNetId")
4355 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004356
Robert Greenwalt7b816022014-04-18 15:25:25 -07004357 // NetworkAgentInfo keyed off its connecting messenger
4358 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004359 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4361 new HashMap<Messenger, NetworkAgentInfo>();
4362
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004363 @GuardedBy("mBlockedAppUids")
4364 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4365
Paul Jensen2c311d62014-11-17 12:34:51 -05004366 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 private final NetworkRequest mDefaultRequest;
4368
Erik Klineda4bfa82015-04-30 12:58:40 +09004369 // Request used to optionally keep mobile data active even when higher
4370 // priority networks like Wi-Fi are active.
4371 private final NetworkRequest mDefaultMobileDataRequest;
4372
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004373 private NetworkAgentInfo getDefaultNetwork() {
4374 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4375 }
4376
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004377 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004378 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004379 }
4380
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004381 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4382 return nri.request.requestId == mDefaultRequest.requestId;
4383 }
4384
Paul Jensen31a94f42015-02-13 14:18:39 -05004385 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004387 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 enforceConnectivityInternalPermission();
4389
Paul Jensen2c311d62014-11-17 12:34:51 -05004390 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4391 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004392 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004393 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4394 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004395 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004396 synchronized (this) {
4397 nai.networkMonitor.systemReady = mSystemReady;
4398 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004399 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4400 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004401 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004403 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 }
4405
4406 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4407 if (VDBG) log("Got NetworkAgent Messenger");
4408 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004409 synchronized (mNetworkForNetId) {
4410 mNetworkForNetId.put(na.network.netId, na);
4411 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4413 NetworkInfo networkInfo = na.networkInfo;
4414 na.networkInfo = null;
4415 updateNetworkInfo(na, networkInfo);
4416 }
4417
4418 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4419 LinkProperties newLp = networkAgent.linkProperties;
4420 int netId = networkAgent.network.netId;
4421
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004422 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4423 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004424 if (networkAgent.clatd != null) {
4425 networkAgent.clatd.fixupLinkProperties(oldLp);
4426 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004427
Paul Jensen992f2522014-04-28 10:33:11 -04004428 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 updateMtu(newLp, oldLp);
4430 // TODO - figure out what to do for clat
4431// for (LinkProperties lp : newLp.getStackedLinks()) {
4432// updateMtu(lp, null);
4433// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004434 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004435
Erik Kline94887872016-04-05 13:30:49 +09004436 updateRoutes(newLp, oldLp, netId);
4437 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004438
Paul Jensen3b759822014-05-13 11:44:01 -04004439 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004440 if (isDefaultNetwork(networkAgent)) {
4441 handleApplyDefaultProxy(newLp.getHttpProxy());
4442 } else {
4443 updateProxy(newLp, oldLp, networkAgent);
4444 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004445 // TODO - move this check to cover the whole function
4446 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004447 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004448 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4449 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004450
4451 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004452 }
4453
Lorenzo Colitti95439462014-10-09 13:44:48 +09004454 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4455 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4456 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004457
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004458 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004459 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4460 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004461 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004462 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004463 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004464 }
Paul Jensen992f2522014-04-28 10:33:11 -04004465
4466 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4467 CompareResult<String> interfaceDiff = new CompareResult<String>();
4468 if (oldLp != null) {
4469 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4470 } else if (newLp != null) {
4471 interfaceDiff.added = newLp.getAllInterfaceNames();
4472 }
4473 for (String iface : interfaceDiff.added) {
4474 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004475 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004476 mNetd.addInterfaceToNetwork(iface, netId);
4477 } catch (Exception e) {
4478 loge("Exception adding interface: " + e);
4479 }
4480 }
4481 for (String iface : interfaceDiff.removed) {
4482 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004483 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004484 mNetd.removeInterfaceFromNetwork(iface, netId);
4485 } catch (Exception e) {
4486 loge("Exception removing interface: " + e);
4487 }
4488 }
4489 }
4490
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004491 /**
4492 * Have netd update routes from oldLp to newLp.
4493 * @return true if routes changed between oldLp and newLp
4494 */
4495 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4497 if (oldLp != null) {
4498 routeDiff = oldLp.compareAllRoutes(newLp);
4499 } else if (newLp != null) {
4500 routeDiff.added = newLp.getAllRoutes();
4501 }
4502
4503 // add routes before removing old in case it helps with continuous connectivity
4504
4505 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4506 for (RouteInfo route : routeDiff.added) {
4507 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004508 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004509 try {
4510 mNetd.addRoute(netId, route);
4511 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004512 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4513 loge("Exception in addRoute for non-gateway: " + e);
4514 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 }
4516 }
4517 for (RouteInfo route : routeDiff.added) {
4518 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004519 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 try {
4521 mNetd.addRoute(netId, route);
4522 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004523 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4524 loge("Exception in addRoute for gateway: " + e);
4525 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
4527 }
4528
4529 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004530 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 try {
4532 mNetd.removeRoute(netId, route);
4533 } catch (Exception e) {
4534 loge("Exception in removeRoute: " + e);
4535 }
4536 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004537 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 }
Erik Kline41368502015-06-17 13:19:54 +09004539
Erik Kline94887872016-04-05 13:30:49 +09004540 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4541 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4542 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 }
Erik Kline94887872016-04-05 13:30:49 +09004544
4545 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004546 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004547 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004548 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004549 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4550 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004551 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004552 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004553 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4554 if (defaultNai != null && defaultNai.network.netId == netId) {
4555 setDefaultDnsSystemProperties(dnses);
4556 }
Erik Kline94887872016-04-05 13:30:49 +09004557 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 }
4559
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004560 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4561 int last = 0;
4562 for (InetAddress dns : dnses) {
4563 ++last;
4564 String key = "net.dns" + last;
4565 String value = dns.getHostAddress();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09004566 mSystemProperties.set(key, value);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004567 }
4568 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4569 String key = "net.dns" + i;
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09004570 mSystemProperties.set(key, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004571 }
4572 mNumDnsEntries = last;
4573 }
4574
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004575 private String getNetworkPermission(NetworkCapabilities nc) {
4576 // TODO: make these permission strings AIDL constants instead.
4577 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4578 return NetworkManagementService.PERMISSION_SYSTEM;
4579 }
4580 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4581 return NetworkManagementService.PERMISSION_NETWORK;
4582 }
4583 return null;
4584 }
4585
Paul Jensen3d194ea2015-06-16 14:27:36 -04004586 /**
4587 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4588 * augmented with any stateful capabilities implied from {@code networkAgent}
4589 * (e.g., validated status and captive portal status).
4590 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004591 * @param oldScore score of the network before any of the changes that prompted us
4592 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004593 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004594 * @param networkCapabilities the new network capabilities.
4595 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004596 private void updateCapabilities(
4597 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004598 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4599 networkCapabilities)) {
4600 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4601 + nai.networkCapabilities + " -> " + networkCapabilities);
4602 }
4603
Paul Jensen3d194ea2015-06-16 14:27:36 -04004604 // Don't modify caller's NetworkCapabilities.
4605 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004606 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004607 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4608 } else {
4609 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4610 }
Paul Jensene0988542015-06-25 15:30:08 -04004611 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004612 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4613 } else {
4614 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4615 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004616 if (nai.isBackgroundNetwork()) {
4617 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4618 } else {
4619 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4620 }
4621
4622 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4623
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004624 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4625 final String newPermission = getNetworkPermission(networkCapabilities);
4626 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004627 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004628 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004629 } catch (RemoteException e) {
4630 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004631 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004632 }
4633
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004634 final NetworkCapabilities prevNc = nai.networkCapabilities;
4635 synchronized (nai) {
4636 nai.networkCapabilities = networkCapabilities;
4637 }
4638 if (nai.getCurrentScore() == oldScore &&
4639 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4640 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4641 // the change we're processing can't affect any requests, it can only affect the listens
4642 // on this network. We might have been called by rematchNetworkAndRequests when a
4643 // network changed foreground state.
4644 processListenRequests(nai, true);
4645 } else {
4646 // If the requestable capabilities have changed or the score changed, we can't have been
4647 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004648 rematchAllNetworksAndRequests(nai, oldScore);
4649 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004650 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 }
4652
Paul Jensenc8b9a742014-09-30 15:37:41 -04004653 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004654 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4655 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004656 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004657 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004658 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4659 }
4660 }
4661
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4663 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004664 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004665 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4666 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004667 }
4668 }
4669
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004670 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4671 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004672 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004673 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004674 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4675 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004676 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004677 sendIntent(nri.mPendingIntent, intent);
4678 }
4679 // else not handled
4680 }
4681
4682 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4683 mPendingIntentWakeLock.acquire();
4684 try {
4685 if (DBG) log("Sending " + pendingIntent);
4686 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4687 } catch (PendingIntent.CanceledException e) {
4688 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4689 mPendingIntentWakeLock.release();
4690 releasePendingNetworkRequest(pendingIntent);
4691 }
4692 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4693 }
4694
4695 @Override
4696 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4697 String resultData, Bundle resultExtras) {
4698 if (DBG) log("Finished sending " + pendingIntent);
4699 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004700 // Release with a delay so the receiving client has an opportunity to put in its
4701 // own request.
4702 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004703 }
4704
Robert Greenwalt9258c642014-03-26 16:47:06 -07004705 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004706 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004707 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004708 Bundle bundle = new Bundle();
4709 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4710 new NetworkRequest(nri.request));
4711 Message msg = Message.obtain();
4712 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4713 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4714 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4715 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004716 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004717 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004718 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004719 break;
4720 }
4721 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4722 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4723 new NetworkCapabilities(networkAgent.networkCapabilities));
4724 break;
4725 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004726 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004727 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4728 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004729 break;
4730 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004732 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004733 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004734 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004735 if (VDBG) {
4736 log("sending notification " + notifyTypeToName(notificationType) +
4737 " for " + nri.request);
4738 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004739 nri.messenger.send(msg);
4740 } catch (RemoteException e) {
4741 // may occur naturally in the race of binder death.
4742 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4743 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004744 }
4745
Paul Jensenc8b9a742014-09-30 15:37:41 -04004746 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004747 if (nai.numRequestNetworkRequests() != 0) {
4748 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4749 NetworkRequest nr = nai.requestAt(i);
4750 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004751 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004752 loge("Dead network still had at least " + nr);
4753 break;
4754 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004755 }
4756 nai.asyncChannel.disconnect();
4757 }
4758
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4760 if (oldNetwork == null) {
4761 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4762 return;
4763 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004764 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004765
4766 // If we get here it means that the last linger timeout for this network expired. So there
4767 // must be no other active linger timers, and we must stop lingering.
4768 oldNetwork.clearLingerState();
4769
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004770 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004771 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004772 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004773 } else {
4774 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004775 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4776 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004777 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004778 }
4779
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004780 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004781 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004782 setupDataActivityTracking(newNetwork);
4783 try {
4784 mNetd.setDefaultNetId(newNetwork.network.netId);
4785 } catch (Exception e) {
4786 loge("Exception setting default network :" + e);
4787 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004788 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004789 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004790 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004791 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004792 }
4793
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004794 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004795 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4796 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4797 NetworkRequest nr = nri.request;
4798 if (!nr.isListen()) continue;
4799 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4800 nai.removeRequest(nri.request.requestId);
4801 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4802 }
4803 }
4804
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004805 if (capabilitiesChanged) {
4806 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4807 }
4808
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004809 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4810 NetworkRequest nr = nri.request;
4811 if (!nr.isListen()) continue;
4812 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4813 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004814 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004815 }
4816 }
4817 }
4818
Paul Jensen2161a8e2014-09-11 11:00:39 -04004819 // Handles a network appearing or improving its score.
4820 //
4821 // - Evaluates all current NetworkRequests that can be
4822 // satisfied by newNetwork, and reassigns to newNetwork
4823 // any such requests for which newNetwork is the best.
4824 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004825 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004826 // needed. A network is needed if it is the best network for
4827 // one or more NetworkRequests, or if it is a VPN.
4828 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004829 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004830 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004831 //
4832 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4833 // networks that have no chance (i.e. even if validated)
4834 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004835 //
4836 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4837 // it does not remove NetworkRequests that other Networks could better satisfy.
4838 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4839 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4840 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004841 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004842 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004843 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4844 // performed to tear down unvalidated networks that have no chance (i.e. even if
4845 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004846 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004847 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004848 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004849 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004850 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004851 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004852
4853 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4854 final int score = newNetwork.getCurrentScore();
4855
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004856 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004857
Paul Jensen2161a8e2014-09-11 11:00:39 -04004858 // Find and migrate to this Network any NetworkRequests for
4859 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004860 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004861 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004862 NetworkCapabilities nc = newNetwork.networkCapabilities;
4863 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004864 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004865 // Process requests in the first pass and listens in the second pass. This allows us to
4866 // change a network's capabilities depending on which requests it has. This is only
4867 // correct if the change in capabilities doesn't affect whether the network satisfies
4868 // requests or not, and doesn't affect the network's score.
4869 if (nri.request.isListen()) continue;
4870
Paul Jensencf4c2c62015-07-01 14:16:32 -04004871 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4872 final boolean satisfies = newNetwork.satisfies(nri.request);
4873 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004874 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004875 log("Network " + newNetwork.name() + " was already satisfying" +
4876 " request " + nri.request.requestId + ". No change.");
4877 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004878 keep = true;
4879 continue;
4880 }
4881
4882 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004883 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004884 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004885 // next check if it's better than any current network we're using for
4886 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004887 if (VDBG) {
4888 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004889 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004890 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004892 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004893 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004894 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004895 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004896 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004897 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004898 affectedNetworks.add(currentNetwork);
4899 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004900 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004901 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004902 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004903 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004904 if (!newNetwork.addRequest(nri.request)) {
4905 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4906 }
4907 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004908 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004909 // Tell NetworkFactories about the new score, so they can stop
4910 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004911 // TODO - this could get expensive if we have alot of requests for this
4912 // network. Think about if there is a way to reduce this. Push
4913 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004914 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004915 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004917 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004918 if (currentNetwork != null) {
4919 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4920 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 }
4922 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004923 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004924 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4925 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004926 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004927 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4928 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4929 // This means this code doesn't have to handle the case where "currentNetwork" no
4930 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4931 if (DBG) {
4932 log("Network " + newNetwork.name() + " stopped satisfying" +
4933 " request " + nri.request.requestId);
4934 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004935 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004936 if (currentNetwork == newNetwork) {
4937 mNetworkForRequestId.remove(nri.request.requestId);
4938 sendUpdatedScoreToFactories(nri.request, 0);
4939 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004940 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4941 newNetwork.name() +
4942 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004943 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004944 // TODO: Technically, sending CALLBACK_LOST here is
4945 // incorrect if there is a replacement network currently
4946 // connected that can satisfy nri, which is a request
4947 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004948 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4949 // so this code is only incorrect for a network that loses
4950 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004951 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952 }
4953 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 if (isNewDefault) {
4955 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004956 makeDefault(newNetwork);
4957 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4958 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004959 // Have a new default network, release the transition wakelock in
4960 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004961 }
4962
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004963 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4964 Slog.wtf(TAG, String.format(
4965 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4966 nc, newNetwork.networkCapabilities));
4967 }
4968 if (newNetwork.getCurrentScore() != score) {
4969 Slog.wtf(TAG, String.format(
4970 "BUG: %s changed score during rematch: %d -> %d",
4971 score, newNetwork.getCurrentScore()));
4972 }
4973
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004974 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004975 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4976 // If the network went from background to foreground or vice versa, we need to update
4977 // its foreground state. It is safe to do this after rematching the requests because
4978 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4979 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004980 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004981 } else {
4982 processListenRequests(newNetwork, false);
4983 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004984
Paul Jensencf4c2c62015-07-01 14:16:32 -04004985 // do this after the default net is switched, but
4986 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004987 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004988
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004989 // Linger any networks that are no longer needed. This should be done after sending the
4990 // available callback for newNetwork.
4991 for (NetworkAgentInfo nai : affectedNetworks) {
4992 updateLingerState(nai, now);
4993 }
4994 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4995 // does not need to be done in any particular order.
4996 updateLingerState(newNetwork, now);
4997
Paul Jensencf4c2c62015-07-01 14:16:32 -04004998 if (isNewDefault) {
4999 // Maintain the illusion: since the legacy API only
5000 // understands one network at a time, we must pretend
5001 // that the current default network disconnected before
5002 // the new one connected.
5003 if (oldDefaultNetwork != null) {
5004 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5005 oldDefaultNetwork, true);
5006 }
5007 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5008 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5009 notifyLockdownVpn(newNetwork);
5010 }
5011
Robert Greenwalt7b816022014-04-18 15:25:25 -07005012 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005013 // Notify battery stats service about this network, both the normal
5014 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005015 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005016 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005017 final IBatteryStats bs = BatteryStatsService.getService();
5018 final int type = newNetwork.networkInfo.getType();
5019
5020 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5021 bs.noteNetworkInterfaceType(baseIface, type);
5022 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5023 final String stackedIface = stacked.getInterfaceName();
5024 bs.noteNetworkInterfaceType(stackedIface, type);
5025 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5026 }
5027 } catch (RemoteException ignored) {
5028 }
5029
Robert Greenwalt152ed372014-12-17 17:19:53 -08005030 // This has to happen after the notifyNetworkCallbacks as that tickles each
5031 // ConnectivityManager instance so that legacy requests correctly bind dns
5032 // requests to this network. The legacy users are listening for this bcast
5033 // and will generally do a dns request so they can ensureRouteToHost and if
5034 // they do that before the callbacks happen they'll use the default network.
5035 //
5036 // TODO: Is there still a race here? We send the broadcast
5037 // after sending the callback, but if the app can receive the
5038 // broadcast before the callback, it might still break.
5039 //
5040 // This *does* introduce a race where if the user uses the new api
5041 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5042 // they may get old info. Reverse this after the old startUsing api is removed.
5043 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005044 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5045 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005046 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005047 // legacy type tracker filters out repeat adds
5048 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5049 }
5050 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005051
5052 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5053 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5054 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5055 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5056 if (newNetwork.isVPN()) {
5057 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005060 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5061 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005062 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005063 if (nai.getLingerExpiry() > 0) {
5064 // This network has active linger timers and no requests, but is not
5065 // lingering. Linger it.
5066 //
5067 // One way (the only way?) this can happen if this network is unvalidated
5068 // and became unneeded due to another network improving its score to the
5069 // point where this network will no longer be able to satisfy any requests
5070 // even if it validates.
5071 updateLingerState(nai, now);
5072 } else {
5073 if (DBG) log("Reaping " + nai.name());
5074 teardownUnneededNetwork(nai);
5075 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005076 }
5077 }
5078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 }
5080
Paul Jensen1c7ba022015-06-16 14:27:36 -04005081 /**
5082 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5083 * being disconnected.
5084 * @param changed If only one Network's score or capabilities have been modified since the last
5085 * time this function was called, pass this Network in this argument, otherwise pass
5086 * null.
5087 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5088 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5089 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5090 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5091 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005092 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005093 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005094 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5095 // to avoid the slowness. It is not simply enough to process just "changed", for
5096 // example in the case where "changed"'s score decreases and another network should begin
5097 // satifying a NetworkRequest that "changed" currently satisfies.
5098
5099 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5100 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5101 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005102 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005103 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005104 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005105 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005106 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5107 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5108 // Rematch higher scoring networks first to prevent requests first matching a lower
5109 // scoring network and then a higher scoring network, which could produce multiple
5110 // callbacks and inadvertently unlinger networks.
5111 Arrays.sort(nais);
5112 for (NetworkAgentInfo nai : nais) {
5113 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005114 // Only reap the last time through the loop. Reaping before all rematching
5115 // is complete could incorrectly teardown a network that hasn't yet been
5116 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005117 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005118 : ReapUnvalidatedNetworks.REAP,
5119 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005120 }
5121 }
5122 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005123
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005124 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005125 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005126 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005127 // For now only update icons for default connection.
5128 // TODO: Update WiFi and cellular icons separately. b/17237507
5129 if (!isDefaultNetwork(nai)) return;
5130
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005131 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005132 // Don't repeat publish.
5133 if (newInetCondition == mDefaultInetConditionPublished) return;
5134
5135 mDefaultInetConditionPublished = newInetCondition;
5136 sendInetConditionBroadcast(nai.networkInfo);
5137 }
5138
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005139 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5140 if (mLockdownTracker != null) {
5141 if (nai != null && nai.isVPN()) {
5142 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5143 } else {
5144 mLockdownTracker.onNetworkInfoChanged();
5145 }
5146 }
5147 }
5148
Robert Greenwalt7b816022014-04-18 15:25:25 -07005149 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005150 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005151 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005152 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005153 synchronized (networkAgent) {
5154 oldInfo = networkAgent.networkInfo;
5155 networkAgent.networkInfo = newInfo;
5156 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005157 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005158
5159 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005160 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5161 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5162 notifyIfacesChangedForNetworkStats();
5163 } else if (VDBG) log("ignoring duplicate network state non-change");
5164 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005165 return;
5166 }
5167 if (DBG) {
5168 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5169 (oldInfo == null ? "null" : oldInfo.getState()) +
5170 " to " + state);
5171 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005172
Robin Lee585e2482016-05-01 23:00:00 +01005173 if (!networkAgent.created
5174 && (state == NetworkInfo.State.CONNECTED
5175 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005176
5177 // A network that has just connected has zero requests and is thus a foreground network.
5178 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5179
Robert Greenwalt7b816022014-04-18 15:25:25 -07005180 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005181 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005182 if (networkAgent.isVPN()) {
5183 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005184 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5185 (networkAgent.networkMisc == null ||
5186 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005187 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005188 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005189 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005190 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005191 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005192 loge("Error creating network " + networkAgent.network.netId + ": "
5193 + e.getMessage());
5194 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005195 }
Paul Jenseneec75412014-08-04 12:21:19 -04005196 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005197 }
5198
5199 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5200 networkAgent.everConnected = true;
5201
Robert Greenwalt7b816022014-04-18 15:25:25 -07005202 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005203 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005204
Paul Jensenca8f16a2014-05-09 12:47:55 -04005205 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005206 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005207
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005208 if (networkAgent.isVPN()) {
5209 // Temporarily disable the default proxy (not global).
5210 synchronized (mProxyLock) {
5211 if (!mDefaultProxyDisabled) {
5212 mDefaultProxyDisabled = true;
5213 if (mGlobalProxy == null && mDefaultProxy != null) {
5214 sendProxyBroadcast(null);
5215 }
5216 }
5217 }
5218 // TODO: support proxy per network.
5219 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005220
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005221 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5222 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5223 // capabilities, so it only needs to be done once on initial connect, not every time the
5224 // network's capabilities change. Note that we do this before rematching the network,
5225 // so we could decide to tear it down immediately afterwards. That's fine though - on
5226 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5227 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005228 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005229
Paul Jensen2161a8e2014-09-11 11:00:39 -04005230 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005231 final long now = SystemClock.elapsedRealtime();
5232 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005233
5234 // This has to happen after matching the requests, because callbacks are just requests.
5235 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005236 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005238 if (networkAgent.isVPN()) {
5239 synchronized (mProxyLock) {
5240 if (mDefaultProxyDisabled) {
5241 mDefaultProxyDisabled = false;
5242 if (mGlobalProxy == null && mDefaultProxy != null) {
5243 sendProxyBroadcast(mDefaultProxy);
5244 }
5245 }
5246 }
5247 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005248 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5249 state == NetworkInfo.State.SUSPENDED) {
5250 // going into or coming out of SUSPEND: rescore and notify
5251 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005252 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005253 }
5254 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5255 ConnectivityManager.CALLBACK_SUSPENDED :
5256 ConnectivityManager.CALLBACK_RESUMED));
5257 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 }
5259 }
5260
Robert Greenwaltac96c522014-06-03 16:43:57 -07005261 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005262 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005263 if (score < 0) {
5264 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5265 "). Bumping score to min of 0");
5266 score = 0;
5267 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005268
Paul Jensen2161a8e2014-09-11 11:00:39 -04005269 final int oldScore = nai.getCurrentScore();
5270 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005271
Paul Jensen85cf78e2015-06-25 13:25:07 -04005272 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005273
Paul Jensenc8b9a742014-09-30 15:37:41 -04005274 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005275 }
5276
Erik Klinec75d4fa2017-02-15 19:59:17 +09005277 // Notify only this one new request of the current state. Transfer all the
5278 // current state by calling NetworkCapabilities and LinkProperties callbacks
5279 // so that callers can be guaranteed to have as close to atomicity in state
5280 // transfer as can be supported by this current API.
5281 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005282 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005283 if (nri.mPendingIntent != null) {
5284 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5285 // Attempt no subsequent state pushes where intents are involved.
5286 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005287 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005288
5289 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5290 // Whether a network is currently suspended is also an important
5291 // element of state to be transferred (it would not otherwise be
5292 // delivered by any currently available mechanism).
5293 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5294 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5295 }
5296 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5297 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005298 }
5299
Robert Greenwalt8d482522015-06-24 13:23:42 -07005300 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005301 // The NetworkInfo we actually send out has no bearing on the real
5302 // state of affairs. For example, if the default connection is mobile,
5303 // and a request for HIPRI has just gone away, we need to pretend that
5304 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5305 // the state to DISCONNECTED, even though the network is of type MOBILE
5306 // and is still connected.
5307 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5308 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005309 if (state != DetailedState.DISCONNECTED) {
5310 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005311 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005312 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005313 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005314 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5315 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5316 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5317 if (info.isFailover()) {
5318 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5319 nai.networkInfo.setFailover(false);
5320 }
5321 if (info.getReason() != null) {
5322 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5323 }
5324 if (info.getExtraInfo() != null) {
5325 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5326 }
5327 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005328 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005329 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005330 if (newDefaultAgent != null) {
5331 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5332 newDefaultAgent.networkInfo);
5333 } else {
5334 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5335 }
5336 }
5337 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5338 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005339 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005340 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005341 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005342 }
5343 }
5344 }
5345
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005346 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005347 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005348 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5349 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005350 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5351 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005352 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5353 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005354 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005355 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005356 } else {
5357 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005359 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005360 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005361
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005362 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5363 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5364 }
5365
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005366 private String notifyTypeToName(int notifyType) {
5367 switch (notifyType) {
5368 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5369 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5370 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5371 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5372 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5373 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5374 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5375 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5376 }
5377 return "UNKNOWN";
5378 }
5379
Jeff Sharkey69736342014-12-08 14:50:12 -08005380 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005381 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5382 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005383 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005384 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005385 try {
5386 mStatsService.forceUpdateIfaces();
5387 } catch (Exception ignored) {
5388 }
5389 }
5390
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005391 @Override
5392 public boolean addVpnAddress(String address, int prefixLength) {
5393 throwIfLockdownEnabled();
5394 int user = UserHandle.getUserId(Binder.getCallingUid());
5395 synchronized (mVpns) {
5396 return mVpns.get(user).addAddress(address, prefixLength);
5397 }
5398 }
5399
5400 @Override
5401 public boolean removeVpnAddress(String address, int prefixLength) {
5402 throwIfLockdownEnabled();
5403 int user = UserHandle.getUserId(Binder.getCallingUid());
5404 synchronized (mVpns) {
5405 return mVpns.get(user).removeAddress(address, prefixLength);
5406 }
5407 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005408
5409 @Override
5410 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5411 throwIfLockdownEnabled();
5412 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005413 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005414 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005415 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005416 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005417 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005418 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005419 }
5420 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005421 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005422
5423 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005424 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005425 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005426 }
5427
5428 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005429 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5430 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5431 enforceKeepalivePermission();
5432 mKeepaliveTracker.startNattKeepalive(
5433 getNetworkAgentInfoForNetwork(network),
5434 intervalSeconds, messenger, binder,
5435 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5436 }
5437
5438 @Override
5439 public void stopKeepalive(Network network, int slot) {
5440 mHandler.sendMessage(mHandler.obtainMessage(
5441 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5442 }
5443
5444 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005445 public void factoryReset() {
5446 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005447
5448 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5449 return;
5450 }
5451
Robin Lee3b3dd942015-05-12 18:14:58 +01005452 final int userId = UserHandle.getCallingUserId();
5453
Stuart Scottf1fb3972015-04-02 18:00:02 -07005454 // Turn airplane mode off
5455 setAirplaneMode(false);
5456
Stuart Scotte3e314d2015-04-20 14:07:45 -07005457 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5458 // Untether
5459 for (String tether : getTetheredIfaces()) {
5460 untether(tether);
5461 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005462 }
5463
Stuart Scotte3e314d2015-04-20 14:07:45 -07005464 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005465 // Remove always-on package
5466 synchronized (mVpns) {
5467 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5468 if (alwaysOnPackage != null) {
5469 setAlwaysOnVpnPackage(userId, null, false);
5470 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5471 }
5472 }
5473
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005474 // Turn Always-on VPN off
5475 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5476 final long ident = Binder.clearCallingIdentity();
5477 try {
5478 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5479 mLockdownEnabled = false;
5480 setLockdownTracker(null);
5481 } finally {
5482 Binder.restoreCallingIdentity(ident);
5483 }
5484 }
5485
Stuart Scotte3e314d2015-04-20 14:07:45 -07005486 // Turn VPN off
5487 VpnConfig vpnConfig = getVpnConfig(userId);
5488 if (vpnConfig != null) {
5489 if (vpnConfig.legacy) {
5490 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5491 } else {
5492 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5493 // in the future without user intervention.
5494 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005495
Victor Changb04a5ea2016-05-30 20:36:30 +01005496 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005497 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005498 }
5499 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005500
5501 Settings.Global.putString(mContext.getContentResolver(),
5502 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005503 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005504
5505 @VisibleForTesting
5506 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5507 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5508 return new NetworkMonitor(context, handler, nai, defaultRequest);
5509 }
Erik Kline48f12f22016-04-14 17:30:59 +09005510
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005511 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005512 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5513 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005514 }
5515
5516 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005517 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5518 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5519 }
5520
Hugo Benichicfddd682016-05-31 16:28:06 +09005521 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005522 int newNetid = NETID_UNSET;
5523 int prevNetid = NETID_UNSET;
5524 int[] transports = new int[0];
5525 boolean hadIPv4 = false;
5526 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005527
Hugo Benichi5f16f762016-04-20 12:09:33 +09005528 if (newNai != null) {
5529 newNetid = newNai.network.netId;
5530 transports = newNai.networkCapabilities.getTransportTypes();
5531 }
5532 if (prevNai != null) {
5533 prevNetid = prevNai.network.netId;
5534 final LinkProperties lp = prevNai.linkProperties;
5535 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5536 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5537 }
5538
Hugo Benichicfddd682016-05-31 16:28:06 +09005539 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5540 }
5541
5542 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5543 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545}