blob: 5467a341463fba9513758c630e59107625716f01 [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;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.SystemProperties;
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
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800211 private Tethering mTethering;
212
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700213 private final PermissionMonitor mPermissionMonitor;
214
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700215 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700216
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700217 @GuardedBy("mVpns")
218 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700219
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700220 private boolean mLockdownEnabled;
221 private LockdownVpnTracker mLockdownTracker;
222
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700223 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
224 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700227 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700228 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600229 @GuardedBy("mRulesLock")
230 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
231 /** Flag indicating if background data is restricted. */
232 @GuardedBy("mRulesLock")
233 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700234
Erik Klineda4bfa82015-04-30 12:58:40 +0900235 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700237 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800240 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700243 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800246 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700249 private String mCurrentTcpBufferSizes;
250
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251 private static final int ENABLED = 1;
252 private static final int DISABLED = 0;
253
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
256 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400259 // Tear down networks that have no chance (e.g. even if validated) of becoming
260 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 // all networks have been rematched against all NetworkRequests.
262 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Don't reap networks. This should be passed when some networks have not yet been
264 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 DONT_REAP
266 };
267
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900268 private enum UnneededFor {
269 LINGER, // Determine whether this network is unneeded and should be lingered.
270 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
271 }
272
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 * used internally to change our mobile data enabled flag
275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277
278 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700280 * from one net to another. Clear happens when we get a new
281 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
282 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286 /**
287 * used internally to reload global proxy settings
288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700291 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400292 * PAC manager has received new port.
293 */
294 private static final int EVENT_PROXY_HAS_CHANGED = 16;
295
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 /**
297 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700298 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 */
300 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
301
Robert Greenwalt7b816022014-04-18 15:25:25 -0700302 /**
303 * used internally when registering NetworkAgents
304 * obj = Messenger
305 */
306 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
307
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 /**
309 * used to add a network request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
313
314 /**
315 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900316 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 * cancel it.
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
321
322 /**
323 * used to add a network listener - no request
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
327
328 /**
329 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400330 * arg1 = UID of caller
331 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
334
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 /**
336 * used internally when registering NetworkFactories
337 * obj = Messenger
338 */
339 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
340
Robert Greenwalt27711812014-06-25 16:45:57 -0700341 /**
342 * used internally to expire a wakelock when transitioning
343 * from one net to another. Expire happens when we fail to find
344 * a new network (typically after 1 minute) -
345 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
346 * a replacement network.
347 */
348 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
349
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700350 /**
351 * Used internally to indicate the system is ready.
352 */
353 private static final int EVENT_SYSTEM_READY = 25;
354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 /**
356 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400357 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 */
359 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
360
361 /**
362 * used to remove a pending intent and its associated network request.
363 * arg1 = UID of caller
364 * obj = PendingIntent
365 */
366 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
367
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 /**
369 * used to specify whether a network should be used even if unvalidated.
370 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
371 * arg2 = whether to remember this choice in the future (1 or 0)
372 * obj = network
373 */
374 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
375
376 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900377 * used to specify whether a network should not be penalized when it becomes unvalidated.
378 */
379 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
380
381 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900382 * used to ask the user to confirm a connection to an unvalidated network.
383 * obj = network
384 */
385 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700386
Erik Klineda4bfa82015-04-30 12:58:40 +0900387 /**
388 * used internally to (re)configure mobile data always-on settings.
389 */
390 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
391
Paul Jensen694f2b82015-06-17 14:15:39 -0400392 /**
393 * used to add a network listener with a pending intent
394 * obj = NetworkRequestInfo
395 */
396 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
397
Erik Klineacdd6392016-07-07 16:50:58 +0900398 /**
399 * Indicates a caller has requested to have its callback invoked with
400 * the latest LinkProperties or NetworkCapabilities.
401 *
402 * arg1 = UID of caller
403 * obj = NetworkRequest
404 */
405 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
406 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
407
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900408 /** Handler thread used for both of the handlers below. */
409 @VisibleForTesting
410 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700411 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700412 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700413 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700414 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700415
Mike Lockwood0f79b542009-08-14 14:18:49 -0400416 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800417 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400418
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700419 private PowerManager.WakeLock mNetTransitionWakeLock;
420 private String mNetTransitionWakeLockCausedBy = "";
421 private int mNetTransitionWakeLockSerialNumber;
422 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800423 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700424
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700425 // used in DBG mode to track inet condition reports
426 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
427 private ArrayList mInetLog;
428
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400430 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700431 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700432 private boolean mDefaultProxyDisabled = false;
433
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400435 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436
Jason Monk602b2322013-07-03 17:04:33 -0400437 private PacManager mPacManager = null;
438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400441 private UserManager mUserManager;
442
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700443 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700444 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445
Robert Greenwalt50393202011-06-21 17:26:14 -0700446 // the set of network types that can only be enabled by system/sig apps
447 List mProtectedNetworks;
448
John Spurlockbf991a82013-06-24 14:20:23 -0400449 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700450
Wink Savilleab9321d2013-06-29 21:10:57 -0700451 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400452
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900454 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900455 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700457 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
458 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700459 private final static int MAX_NET_ID = 65535;
460 private int mNextNetId = MIN_NET_ID;
461
Robert Greenwalt34524f02014-05-18 16:22:10 -0700462 // sequence number of NetworkRequests
463 private int mNextNetworkRequestId = 1;
464
Erik Kline7523eb32015-07-09 18:24:03 +0900465 // NetworkRequest activity String log entries.
466 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
467 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
468
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 // NetworkInfo blocked and unblocked String log entries
470 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
471 private static final int MAX_NETWORK_INFO_LOGS = 100;
472 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
473
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700474 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
475 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400476 private static class ValidationLog {
477 final Network mNetwork;
478 final String mNetworkExtraInfo;
479 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
482 mNetwork = network;
483 mNetworkExtraInfo = networkExtraInfo;
484 mLog = log;
485 }
486 }
487 private final ArrayDeque<ValidationLog> mValidationLogs =
488 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
489
490 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700491 synchronized(mValidationLogs) {
492 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
493 mValidationLogs.removeLast();
494 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400495 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 }
497 }
498
Hugo Benichif9fdf872016-07-28 17:53:06 +0900499 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900500
Erik Kline065ab6e2016-10-02 18:02:14 +0900501 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900502 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900503
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700504 /**
505 * Implements support for the legacy "one network per network type" model.
506 *
507 * We used to have a static array of NetworkStateTrackers, one for each
508 * network type, but that doesn't work any more now that we can have,
509 * for example, more that one wifi network. This class stores all the
510 * NetworkAgentInfo objects that support a given type, but the legacy
511 * API will only see the first one.
512 *
513 * It serves two main purposes:
514 *
515 * 1. Provide information about "the network for a given type" (since this
516 * API only supports one).
517 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
518 * the first network for a given type changes, or if the default network
519 * changes.
520 */
521 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900523 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 /**
527 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
528 * Each list holds references to all NetworkAgentInfos that are used to
529 * satisfy requests for that network type.
530 *
531 * This array is built out at startup such that an unsupported network
532 * doesn't get an ArrayList instance, making this a tristate:
533 * unsupported, supported but not active and active.
534 *
535 * The actual lists are populated when we scan the network types that
536 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 *
538 * Threading model:
539 * - addSupportedType() is only called in the constructor
540 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
541 * They are therefore not thread-safe with respect to each other.
542 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
543 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
544 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900546 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700547
548 public LegacyTypeTracker() {
549 mTypeLists = (ArrayList<NetworkAgentInfo>[])
550 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
551 }
552
553 public void addSupportedType(int type) {
554 if (mTypeLists[type] != null) {
555 throw new IllegalStateException(
556 "legacy list for type " + type + "already initialized");
557 }
558 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
559 }
560
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 public boolean isTypeSupported(int type) {
562 return isNetworkTypeValid(type) && mTypeLists[type] != null;
563 }
564
565 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900566 synchronized (mTypeLists) {
567 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
568 return mTypeLists[type].get(0);
569 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900571 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 }
573
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900578 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 }
581 }
582
583 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 public void add(int type, NetworkAgentInfo nai) {
585 if (!isTypeSupported(type)) {
586 return; // Invalid network type.
587 }
588 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
589
590 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
591 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 return;
593 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 synchronized (mTypeLists) {
595 list.add(nai);
596 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900597
598 // 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 +0900599 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900600 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
602 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700604 }
605
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900607 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list == null || list.isEmpty()) {
610 return;
611 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 synchronized (mTypeLists) {
615 if (!list.remove(nai)) {
616 return;
617 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 final DetailedState state = DetailedState.DISCONNECTED;
621
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(nai, state, type, wasDefault);
624 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626
627 if (!list.isEmpty() && wasFirstNetwork) {
628 if (DBG) log("Other network available for type " + type +
629 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700631 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
632 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 }
634 }
635
636 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
638 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700639 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
642 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700643
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 // send out another legacy broadcast - currently only used for suspend/unsuspend
645 // toggle
646 public void update(NetworkAgentInfo nai) {
647 final boolean isDefault = isDefaultNetwork(nai);
648 final DetailedState state = nai.networkInfo.getDetailedState();
649 for (int type = 0; type < mTypeLists.length; type++) {
650 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700651 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 final boolean isFirst = contains && (nai == list.get(0));
653 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700654 maybeLogBroadcast(nai, state, type, isDefault);
655 sendLegacyNetworkBroadcast(nai, state, type);
656 }
657 }
658 }
659
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 private String naiToString(NetworkAgentInfo nai) {
661 String name = (nai != null) ? nai.name() : "null";
662 String state = (nai.networkInfo != null) ?
663 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
664 "???/???";
665 return name + " " + state;
666 }
667
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println("mLegacyTypeTracker:");
670 pw.increaseIndent();
671 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 pw.println();
676 pw.println("Current state:");
677 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 synchronized (mTypeLists) {
679 for (int type = 0; type < mTypeLists.length; type++) {
680 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
681 for (NetworkAgentInfo nai : mTypeLists[type]) {
682 pw.println(type + " " + naiToString(nai));
683 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900684 }
685 }
686 pw.decreaseIndent();
687 pw.decreaseIndent();
688 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700689 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
692
Jeff Sharkey899223b2012-08-04 15:24:58 -0700693 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700694 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900695 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
696 }
697
698 @VisibleForTesting
699 protected ConnectivityService(Context context, INetworkManagementService netManager,
700 INetworkStatsService statsService, INetworkPolicyManager policyManager,
701 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800703
Hugo Benichif9fdf872016-07-28 17:53:06 +0900704 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900705 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900706 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900707 mNetworkRequests.put(mDefaultRequest, defaultNRI);
708 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900709
710 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900711 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700712
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900713 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900714 mHandlerThread.start();
715 mHandler = new InternalHandler(mHandlerThread.getLooper());
716 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700717
Jeremy Joslin79294842014-12-03 17:15:28 -0800718 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
719 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
720
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900721 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
722
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700723 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700724 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800725 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700727 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700728 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700729
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600731 mPolicyManager.setConnectivityListener(mPolicyListener);
732 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700733 } catch (RemoteException e) {
734 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700735 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 }
737
738 final PowerManager powerManager = (PowerManager) context.getSystemService(
739 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700740 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
741 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
742 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800743 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700745 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746
Wink Saville51f456f2013-04-23 14:26:51 -0700747 // TODO: What is the "correct" way to do determine if this is a wifi only device?
748 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
749 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 String[] naStrings = context.getResources().getStringArray(
751 com.android.internal.R.array.networkAttributes);
752 for (String naString : naStrings) {
753 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700754 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700755 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700756 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800757 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700758 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700760 }
Wink Saville51f456f2013-04-23 14:26:51 -0700761 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
762 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
763 n.type);
764 continue;
765 }
Wink Saville975c8482011-04-07 14:23:45 -0700766 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800767 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700768 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769 continue;
770 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700771 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700772
Wink Saville975c8482011-04-07 14:23:45 -0700773 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 mNetworksDefined++;
775 } catch(Exception e) {
776 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700777 }
778 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700779
780 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
781 if (mNetConfigs[TYPE_VPN] == null) {
782 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
783 // don't need to add TYPE_VPN to mNetConfigs.
784 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
785 mNetworksDefined++; // used only in the log() statement below.
786 }
787
Wink Saville5e56bc52013-07-29 15:00:57 -0700788 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700789
Robert Greenwalt50393202011-06-21 17:26:14 -0700790 mProtectedNetworks = new ArrayList<Integer>();
791 int[] protectedNetworks = context.getResources().getIntArray(
792 com.android.internal.R.array.config_protectedNetworks);
793 for (int p : protectedNetworks) {
794 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
795 mProtectedNetworks.add(p);
796 } else {
797 if (DBG) loge("Ignoring protectedNetwork " + p);
798 }
799 }
800
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700801 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
802 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700803
Christopher Wiley497c1472016-10-11 13:26:03 -0700804 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
805 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800806
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700807 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
808
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700809 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700810 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100811 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700812 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700813 intentFilter.addAction(Intent.ACTION_USER_ADDED);
814 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000815 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700816 mContext.registerReceiverAsUser(
817 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900818
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700819 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700820 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700821 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700822 } catch (RemoteException e) {
823 loge("Error registering observer :" + e);
824 }
825
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700826 if (DBG) {
827 mInetLog = new ArrayList();
828 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700829
Erik Klineda4bfa82015-04-30 12:58:40 +0900830 mSettingsObserver = new SettingsObserver(mContext, mHandler);
831 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800832
John Spurlockbf991a82013-06-24 14:20:23 -0400833 mDataConnectionStats = new DataConnectionStats(mContext);
834 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400835
Jason Monkdecd2952013-10-10 14:02:51 -0400836 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700837
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400838 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900839
840 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900841 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
842 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900843
844 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
845 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
846 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
847 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
848 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
849 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
850 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900851
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900852 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900853 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900854 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700856
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900857 private NetworkRequest createInternetRequestForTransport(
858 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900859 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900860 netCap.addCapability(NET_CAPABILITY_INTERNET);
861 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900862 if (transportType > -1) {
863 netCap.addTransportType(transportType);
864 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900865 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900866 }
867
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900868 // Used only for testing.
869 // TODO: Delete this and either:
870 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
871 // changing ContentResolver to make registerContentObserver non-final).
872 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
873 // by subclassing SettingsObserver.
874 @VisibleForTesting
875 void updateMobileDataAlwaysOn() {
876 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
877 }
878
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 private void handleMobileDataAlwaysOn() {
880 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900881 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900882 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
883 if (enable == isEnabled) {
884 return; // Nothing to do.
885 }
886
887 if (enable) {
888 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900889 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900890 } else {
891 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
892 }
893 }
894
895 private void registerSettingsCallbacks() {
896 // Watch for global HTTP proxy changes.
897 mSettingsObserver.observe(
898 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
899 EVENT_APPLY_GLOBAL_HTTP_PROXY);
900
901 // Watch for whether or not to keep mobile data always on.
902 mSettingsObserver.observe(
903 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
904 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
905 }
906
Robert Greenwalt34524f02014-05-18 16:22:10 -0700907 private synchronized int nextNetworkRequestId() {
908 return mNextNetworkRequestId++;
909 }
910
Paul Jensen67b0b072015-06-10 11:22:17 -0400911 @VisibleForTesting
912 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400913 synchronized (mNetworkForNetId) {
914 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
915 int netId = mNextNetId;
916 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
917 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500918 if (!mNetIdInUse.get(netId)) {
919 mNetIdInUse.put(netId, true);
920 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400921 }
922 }
923 }
924 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700925 }
926
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600927 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600929 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
930 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800931 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 state = nai.getNetworkState();
933 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 final NetworkInfo info = new NetworkInfo(networkType, 0,
936 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800937 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
938 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600939 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
940 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600942 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 return state;
944 } else {
945 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400947 }
948
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
950 if (network == null) {
951 return null;
952 }
953 synchronized (mNetworkForNetId) {
954 return mNetworkForNetId.get(network.netId);
955 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600956 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900958 private Network[] getVpnUnderlyingNetworks(int uid) {
959 if (!mLockdownEnabled) {
960 int user = UserHandle.getUserId(uid);
961 synchronized (mVpns) {
962 Vpn vpn = mVpns.get(user);
963 if (vpn != null && vpn.appliesToUid(uid)) {
964 return vpn.getUnderlyingNetworks();
965 }
966 }
967 }
968 return null;
969 }
970
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400972 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800973
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900974 final Network[] networks = getVpnUnderlyingNetworks(uid);
975 if (networks != null) {
976 // getUnderlyingNetworks() returns:
977 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
978 // empty array => the VPN explicitly said "no default network".
979 // non-empty array => the VPN specified one or more default networks; we use the
980 // first one.
981 if (networks.length > 0) {
982 nai = getNetworkAgentInfoForNetwork(networks[0]);
983 } else {
984 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800985 }
986 }
987
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800988 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600989 return nai.getNetworkState();
990 } else {
991 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400993 }
994
995 /**
996 * Check if UID should be blocked from using the network with the given LinkProperties.
997 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600998 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
999 boolean ignoreBlocked) {
1000 // Networks aren't blocked when ignoring blocked status
1001 if (ignoreBlocked) return false;
1002 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001003 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001004
1005 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001006 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001007
Robin Lee17e61832016-05-09 13:46:28 +01001008 synchronized (mVpns) {
1009 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1010 if (vpn != null && vpn.isBlockingUid(uid)) {
1011 return true;
1012 }
1013 }
1014
Robert Greenwalt12e67352014-05-13 21:41:06 -07001015 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001016 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001017 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001018 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001020
Felipe Lemed31a97f2016-05-06 14:53:50 -07001021 boolean allowed = true;
1022 // Check Data Saver Mode first...
1023 if (networkMetered) {
1024 if ((uidRules & RULE_REJECT_METERED) != 0) {
1025 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1026 // Explicitly blacklisted.
1027 allowed = false;
1028 } else {
1029 allowed = !mRestrictBackground
1030 || (uidRules & RULE_ALLOW_METERED) != 0
1031 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1032 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1033 + " mRestrictBackground=" + mRestrictBackground
1034 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1035 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1036 + ": " + allowed);
1037 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001038 }
Felipe Leme781ba142016-05-09 16:24:48 -07001039 // ...then power restrictions.
1040 if (allowed) {
1041 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001042 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001043 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001044 }
1045 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
1047
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001048 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001049 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1050 return;
1051 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001052 boolean removed = false;
1053 boolean added = false;
1054 synchronized (mBlockedAppUids) {
1055 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1056 added = true;
1057 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1058 removed = true;
1059 }
1060 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001061 if (added) {
1062 log("Returning blocked NetworkInfo to uid=" + uid);
1063 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1064 } else if (removed) {
1065 log("Returning unblocked NetworkInfo to uid=" + uid);
1066 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1067 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001068 }
1069
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1072 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1073 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1074 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001076 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1078
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001080 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 if (mLockdownTracker != null) {
1083 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001084 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085
1086 // TODO: apply metered state closer to NetworkAgentInfo
1087 final long token = Binder.clearCallingIdentity();
1088 try {
1089 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1090 } catch (RemoteException e) {
1091 } finally {
1092 Binder.restoreCallingIdentity(token);
1093 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001094 }
1095
1096 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * Return NetworkInfo for the active (i.e., connected) network interface.
1098 * It is assumed that at most one network is active at a time. If more
1099 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001100 * @return the info for the active network, or {@code null} if none is
1101 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001103 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 enforceAccessPermission();
1106 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1110 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112
Paul Jensen31a94f42015-02-13 14:18:39 -05001113 @Override
1114 public Network getActiveNetwork() {
1115 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001117 }
1118
1119 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001121 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001123 }
1124
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001126 final int user = UserHandle.getUserId(uid);
1127 int vpnNetId = NETID_UNSET;
1128 synchronized (mVpns) {
1129 final Vpn vpn = mVpns.get(user);
1130 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1131 }
1132 NetworkAgentInfo nai;
1133 if (vpnNetId != NETID_UNSET) {
1134 synchronized (mNetworkForNetId) {
1135 nai = mNetworkForNetId.get(vpnNetId);
1136 }
1137 if (nai != null) return nai.network;
1138 }
1139 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 if (nai != null
1141 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1142 nai = null;
1143 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001144 return nai != null ? nai.network : null;
1145 }
1146
Lorenzo Colitti18660282016-07-04 12:55:44 +09001147 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001148 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1149 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 final int uid = Binder.getCallingUid();
1151 NetworkState state = getUnfilteredActiveNetworkState(uid);
1152 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001153 }
1154
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 }
1162
1163 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 public NetworkInfo getNetworkInfo(int networkType) {
1165 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001167 if (getVpnUnderlyingNetworks(uid) != null) {
1168 // A VPN is active, so we may need to return one of its underlying networks. This
1169 // information is not available in LegacyTypeTracker, so we have to get it from
1170 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001175 }
1176 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 }
1180
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 return state.networkInfo;
1189 } else {
1190 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001191 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001192 }
1193
1194 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public NetworkInfo[] getAllNetworkInfo() {
1196 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001197 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001198 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1199 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 NetworkInfo info = getNetworkInfo(networkType);
1201 if (info != null) {
1202 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001205 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001208 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001209 public Network getNetworkForType(int networkType) {
1210 enforceAccessPermission();
1211 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001212 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1213 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001215 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 }
1218
1219 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 public Network[] getAllNetworks() {
1221 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001223 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001225 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001227 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 }
1230
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001231 @Override
1232 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1233 // The basic principle is: if an app's traffic could possibly go over a
1234 // network, without the app doing anything multinetwork-specific,
1235 // (hence, by "default"), then include that network's capabilities in
1236 // the array.
1237 //
1238 // In the normal case, app traffic only goes over the system's default
1239 // network connection, so that's the only network returned.
1240 //
1241 // With a VPN in force, some app traffic may go into the VPN, and thus
1242 // over whatever underlying networks the VPN specifies, while other app
1243 // traffic may go over the system default network (e.g.: a split-tunnel
1244 // VPN, or an app disallowed by the VPN), so the set of networks
1245 // returned includes the VPN's underlying networks and the system
1246 // default.
1247 enforceAccessPermission();
1248
1249 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1250
1251 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001252 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001253 if (nc != null) {
1254 result.put(nai.network, nc);
1255 }
1256
1257 if (!mLockdownEnabled) {
1258 synchronized (mVpns) {
1259 Vpn vpn = mVpns.get(userId);
1260 if (vpn != null) {
1261 Network[] networks = vpn.getUnderlyingNetworks();
1262 if (networks != null) {
1263 for (Network network : networks) {
1264 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001265 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001266 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001267 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001268 }
1269 }
1270 }
1271 }
1272 }
1273 }
1274
1275 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1276 out = result.values().toArray(out);
1277 return out;
1278 }
1279
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001281 public boolean isNetworkSupported(int networkType) {
1282 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001283 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001284 }
1285
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001286 /**
1287 * Return LinkProperties for the active (i.e., connected) default
1288 * network interface. It is assumed that at most one default network
1289 * is active at a time. If more than one is active, it is indeterminate
1290 * which will be returned.
1291 * @return the ip properties for the active network, or {@code null} if
1292 * none is active
1293 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001294 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001295 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001296 enforceAccessPermission();
1297 final int uid = Binder.getCallingUid();
1298 NetworkState state = getUnfilteredActiveNetworkState(uid);
1299 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 }
1301
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001302 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001303 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001305 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1306 if (nai != null) {
1307 synchronized (nai) {
1308 return new LinkProperties(nai.linkProperties);
1309 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001310 }
1311 return null;
1312 }
1313
Robert Greenwalt12e67352014-05-13 21:41:06 -07001314 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001315 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001316 public LinkProperties getLinkProperties(Network network) {
1317 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001318 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001319 if (nai != null) {
1320 synchronized (nai) {
1321 return new LinkProperties(nai.linkProperties);
1322 }
1323 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 return null;
1325 }
1326
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001327 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 if (nai != null) {
1329 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001330 if (nai.networkCapabilities != null) {
1331 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001332 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 }
1334 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001335 return null;
1336 }
1337
1338 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001339 public NetworkCapabilities getNetworkCapabilities(Network network) {
1340 enforceAccessPermission();
1341 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1342 }
1343
1344 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001345 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001346 // Require internal since we're handing out IMSI details
1347 enforceConnectivityInternalPermission();
1348
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001349 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001350 for (Network network : getAllNetworks()) {
1351 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1352 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001353 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001354 }
1355 }
1356 return result.toArray(new NetworkState[result.size()]);
1357 }
1358
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001359 @Override
1360 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1361 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001362 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001363 final long token = Binder.clearCallingIdentity();
1364 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001365 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1366 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001367 try {
1368 return mPolicyManager.getNetworkQuotaInfo(state);
1369 } catch (RemoteException e) {
1370 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001371 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001372 return null;
1373 } finally {
1374 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001375 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001376 }
1377
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001378 @Override
1379 public boolean isActiveNetworkMetered() {
1380 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001381
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001382 final NetworkInfo info = getActiveNetworkInfo();
1383 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001384 }
1385
Jeff Sharkey216c1812012-08-05 14:29:23 -07001386 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1387 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001388 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001389 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001390 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001391 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001392 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001393
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001394 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * Ensure that a network route exists to deliver traffic to the specified
1396 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001397 * @param networkType the type of the network over which traffic to the
1398 * specified host is to be routed
1399 * @param hostAddress the IP address of the host to which the route is
1400 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 * @return {@code true} on success, {@code false} on failure
1402 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001403 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001404 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001406 if (mProtectedNetworks.contains(networkType)) {
1407 enforceConnectivityInternalPermission();
1408 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409
Chad Brubakerc0234532014-02-14 13:24:29 -08001410 InetAddress addr;
1411 try {
1412 addr = InetAddress.getByAddress(hostAddress);
1413 } catch (UnknownHostException e) {
1414 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1415 return false;
1416 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001419 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 return false;
1421 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001422
1423 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1424 if (nai == null) {
1425 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1426 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1427 } else {
1428 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1429 }
1430 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001431 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001432
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001433 DetailedState netState;
1434 synchronized (nai) {
1435 netState = nai.networkInfo.getDetailedState();
1436 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001437
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001439 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001440 log("requestRouteToHostAddress on down network "
1441 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001442 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001443 }
1444 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001446
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001447 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001448 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001449 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001450 LinkProperties lp;
1451 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001452 synchronized (nai) {
1453 lp = nai.linkProperties;
1454 netId = nai.network.netId;
1455 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001456 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001457 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1458 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 } finally {
1460 Binder.restoreCallingIdentity(token);
1461 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001462 }
1463
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001464 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001465 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001467 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001469 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 if (bestRoute.getGateway().equals(addr)) {
1471 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001472 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001473 } else {
1474 // if we will connect to this through another route, add a direct route
1475 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001476 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001477 }
1478 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001479 if (DBG) log("Adding legacy route " + bestRoute +
1480 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001481 try {
1482 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1483 } catch (Exception e) {
1484 // never crash - catch them all
1485 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001486 return false;
1487 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001488 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001491 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1492 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001493 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001494 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001496 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 }
1498
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001499 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001500 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001501 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 if (oldRules == uidRules) return;
1503
Felipe Leme781ba142016-05-09 16:24:48 -07001504 if (uidRules == RULE_NONE) {
1505 mUidRules.delete(uid);
1506 } else {
1507 mUidRules.put(uid, uidRules);
1508 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 }
1510
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 // TODO: notify UID when it has requested targeted updates
1512 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001513
1514 @Override
1515 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001516 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001517 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001518 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001519 }
1520
1521 synchronized (mRulesLock) {
1522 mMeteredIfaces.clear();
1523 for (String iface : meteredIfaces) {
1524 mMeteredIfaces.add(iface);
1525 }
1526 }
1527 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001528
1529 @Override
1530 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1531 // caller is NPMS, since we only register with them
1532 if (LOGD_RULES) {
1533 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1534 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001535
1536 synchronized (mRulesLock) {
1537 mRestrictBackground = restrictBackground;
1538 }
1539
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001540 if (restrictBackground) {
1541 log("onRestrictBackgroundChanged(true): disabling tethering");
1542 mTethering.untetherAll();
1543 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001544 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001545
1546 @Override
1547 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1548 if (LOGD_RULES) {
1549 // caller is NPMS, since we only register with them
1550 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1551 + whitelisted + ")");
1552 }
1553 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001554 @Override
1555 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1556 if (LOGD_RULES) {
1557 // caller is NPMS, since we only register with them
1558 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1559 + blacklisted + ")");
1560 }
1561 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001562 };
1563
Robin Lee3b3dd942015-05-12 18:14:58 +01001564 /**
1565 * Require that the caller is either in the same user or has appropriate permission to interact
1566 * across users.
1567 *
1568 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1569 */
1570 private void enforceCrossUserPermission(int userId) {
1571 if (userId == UserHandle.getCallingUserId()) {
1572 // Not a cross-user call.
1573 return;
1574 }
1575 mContext.enforceCallingOrSelfPermission(
1576 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1577 "ConnectivityService");
1578 }
1579
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001580 private void enforceInternetPermission() {
1581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.INTERNET,
1583 "ConnectivityService");
1584 }
1585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.ACCESS_NETWORK_STATE,
1589 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
1591
1592 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001593 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001596 private void enforceTetherAccessPermission() {
1597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.ACCESS_NETWORK_STATE,
1599 "ConnectivityService");
1600 }
1601
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001602 private void enforceConnectivityInternalPermission() {
1603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1605 "ConnectivityService");
1606 }
1607
Hugo Benichi514da602016-07-19 15:59:27 +09001608 private void enforceConnectivityRestrictedNetworksPermission() {
1609 try {
1610 mContext.enforceCallingOrSelfPermission(
1611 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1612 "ConnectivityService");
1613 return;
1614 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1615 enforceConnectivityInternalPermission();
1616 }
1617
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001618 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001619 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001620 }
1621
Lorenzo Colitti18660282016-07-04 12:55:44 +09001622 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001623 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001624 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001625 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001626 }
1627
1628 private void sendInetConditionBroadcast(NetworkInfo info) {
1629 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1630 }
1631
Wink Saville628b0852011-08-04 15:01:58 -07001632 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001633 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001634 info = new NetworkInfo(info);
1635 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001636 }
1637
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001638 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001640 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (info.isFailover()) {
1642 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1643 info.setFailover(false);
1644 }
1645 if (info.getReason() != null) {
1646 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1647 }
1648 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001649 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1650 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001652 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001653 return intent;
1654 }
1655
1656 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1657 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1658 }
1659
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001660 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001661 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1662 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1663 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001664 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001665 final long ident = Binder.clearCallingIdentity();
1666 try {
1667 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1668 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1669 } finally {
1670 Binder.restoreCallingIdentity(ident);
1671 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001672 }
1673
Mike Lockwood0f79b542009-08-14 14:18:49 -04001674 private void sendStickyBroadcast(Intent intent) {
1675 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001676 if (!mSystemReady) {
1677 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001678 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001679 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001680 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001681 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001682 }
1683
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001684 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001685 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001686 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001687 final NetworkInfo ni = intent.getParcelableExtra(
1688 ConnectivityManager.EXTRA_NETWORK_INFO);
1689 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1690 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1691 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001692 } else {
1693 BroadcastOptions opts = BroadcastOptions.makeBasic();
1694 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1695 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001696 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001697 final IBatteryStats bs = BatteryStatsService.getService();
1698 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001699 bs.noteConnectivityChanged(intent.getIntExtra(
1700 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1701 ni != null ? ni.getState().toString() : "?");
1702 } catch (RemoteException e) {
1703 }
1704 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001705 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001706 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 } finally {
1708 Binder.restoreCallingIdentity(ident);
1709 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001710 }
1711 }
1712
1713 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001714 loadGlobalProxy();
1715
Mike Lockwood0f79b542009-08-14 14:18:49 -04001716 synchronized(this) {
1717 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001718 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001719 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001720 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 }
1722 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001723 // load the global proxy at startup
1724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001725
Robin Lee244ce8e2016-01-05 18:03:46 +00001726 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1727 // for user to unlock device too.
1728 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001729
Erik Klineda4bfa82015-04-30 12:58:40 +09001730 // Configure whether mobile data is always on.
1731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1732
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001734
1735 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001740 *
1741 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001742 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001743 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1745 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001746
1747 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001749
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 if (networkAgent.networkCapabilities.hasTransport(
1751 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001752 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1753 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001754 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001755 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 } else if (networkAgent.networkCapabilities.hasTransport(
1757 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001758 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1759 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001760 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001762 } else {
1763 // do not track any other networks
1764 timeout = 0;
1765 }
1766
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001768 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001769 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001770 } catch (Exception e) {
1771 // You shall not crash!
1772 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001773 }
1774 }
1775 }
1776
1777 /**
1778 * Remove data activity tracking when network disconnects.
1779 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001780 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1781 final String iface = networkAgent.linkProperties.getInterfaceName();
1782 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001783
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1785 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001786 try {
1787 // the call fails silently if no idletimer setup for this interface
1788 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001789 } catch (Exception e) {
1790 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001791 }
1792 }
1793 }
1794
1795 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001796 * Reads the network specific MTU size from reources.
1797 * and set it on it's iface.
1798 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001799 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1800 final String iface = newLp.getInterfaceName();
1801 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001802 if (oldLp == null && mtu == 0) {
1803 // Silently ignore unset MTU value.
1804 return;
1805 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001806 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1807 if (VDBG) log("identical MTU - not setting");
1808 return;
1809 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001810 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001811 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001812 return;
1813 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001814
w1997615afd812014-08-05 15:18:11 -07001815 // Cannot set MTU without interface name
1816 if (TextUtils.isEmpty(iface)) {
1817 loge("Setting MTU size with null iface.");
1818 return;
1819 }
1820
Robert Greenwalt7b816022014-04-18 15:25:25 -07001821 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001822 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 mNetd.setMtu(iface, mtu);
1824 } catch (Exception e) {
1825 Slog.e(TAG, "exception in setMtu()" + e);
1826 }
1827 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001828
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001829 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001830 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1831
1832 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001833 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001834 protected int getDefaultTcpRwnd() {
1835 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1836 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001837
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001838 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1839 if (isDefaultNetwork(nai) == false) {
1840 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001841 }
1842
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1844 String[] values = null;
1845 if (tcpBufferSizes != null) {
1846 values = tcpBufferSizes.split(",");
1847 }
1848
1849 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001850 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001851 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1852 values = tcpBufferSizes.split(",");
1853 }
1854
1855 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1856
1857 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001858 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001859
1860 final String prefix = "/sys/kernel/ipv4/tcp_";
1861 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1862 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1863 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1864 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1865 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1866 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1867 mCurrentTcpBufferSizes = tcpBufferSizes;
1868 } catch (IOException e) {
1869 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001870 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001871
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001872 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001873 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1875 if (rwndValue != 0) {
1876 SystemProperties.set(sysctlKey, rwndValue.toString());
1877 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001878 }
1879
Mattias Falk8b47b362011-08-23 14:15:13 +02001880 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001881 /*
1882 * Tell the VMs to toss their DNS caches
1883 */
1884 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1885 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001886 /*
1887 * Connectivity events can happen before boot has completed ...
1888 */
1889 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001890 final long ident = Binder.clearCallingIdentity();
1891 try {
1892 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1893 } finally {
1894 Binder.restoreCallingIdentity(ident);
1895 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 }
1897
Robert Greenwalt562cc542014-05-15 18:07:26 -07001898 @Override
1899 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001900 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1901 NETWORK_RESTORE_DELAY_PROP_NAME);
1902 if(restoreDefaultNetworkDelayStr != null &&
1903 restoreDefaultNetworkDelayStr.length() != 0) {
1904 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001905 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906 } catch (NumberFormatException e) {
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001909 // if the system property isn't set, use the value for the apn type
1910 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1911
1912 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1913 (mNetConfigs[networkType] != null)) {
1914 ret = mNetConfigs[networkType].restoreTime;
1915 }
1916 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 }
1918
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001919 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001920 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001921 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001922 }
1923 return false;
1924 }
1925
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001926 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1927 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1928 final long DIAG_TIME_MS = 5000;
1929 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1930 // Start gathering diagnostic information.
1931 netDiags.add(new NetworkDiagnostics(
1932 nai.network,
1933 new LinkProperties(nai.linkProperties), // Must be a copy.
1934 DIAG_TIME_MS));
1935 }
1936
1937 for (NetworkDiagnostics netDiag : netDiags) {
1938 pw.println();
1939 netDiag.waitForMeasurements();
1940 netDiag.dump(pw);
1941 }
1942 }
1943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001945 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1946 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001947 if (mContext.checkCallingOrSelfPermission(
1948 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001950 pw.println("Permission Denial: can't dump ConnectivityService " +
1951 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1952 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 return;
1954 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001956 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001957 dumpNetworkDiagnostics(pw);
1958 return;
1959 }
Erik Kline379747a2015-06-05 17:47:34 +09001960
Lorenzo Colittie3805462015-06-03 11:18:24 +09001961 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001962 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001965 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001966 pw.println();
1967
Paul Jensen85cf78e2015-06-25 13:25:07 -04001968 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001969 pw.print("Active default network: ");
1970 if (defaultNai == null) {
1971 pw.println("none");
1972 } else {
1973 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001975 pw.println();
1976
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001977 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001978 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1980 pw.println(nai.toString());
1981 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001982 pw.println(String.format(
1983 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1984 nai.numForegroundNetworkRequests(),
1985 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1986 nai.numBackgroundNetworkRequests(),
1987 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001989 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1990 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001991 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.decreaseIndent();
1993 pw.println("Lingered:");
1994 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001995 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001996 pw.decreaseIndent();
1997 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001998 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001999 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002000 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002001
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002002 pw.println("Metered Interfaces:");
2003 pw.increaseIndent();
2004 for (String value : mMeteredIfaces) {
2005 pw.println(value);
2006 }
2007 pw.decreaseIndent();
2008 pw.println();
2009
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002010 pw.print("Restrict background: ");
2011 pw.println(mRestrictBackground);
2012 pw.println();
2013
Felipe Leme46c4fc32016-05-04 09:21:43 -07002014 pw.println("Status for known UIDs:");
2015 pw.increaseIndent();
2016 final int size = mUidRules.size();
2017 for (int i = 0; i < size; i++) {
2018 final int uid = mUidRules.keyAt(i);
2019 pw.print("UID=");
2020 pw.print(uid);
2021 final int uidRules = mUidRules.get(uid, RULE_NONE);
2022 pw.print(" rules=");
2023 pw.print(uidRulesToString(uidRules));
2024 pw.println();
2025 }
2026 pw.println();
2027 pw.decreaseIndent();
2028
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002029 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002030 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002031 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2032 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002033 }
2034 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002035 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002036
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002037 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002038
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002039 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002040 pw.print("mNetTransitionWakeLock: currently " +
2041 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2042 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2043 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2044 } else {
2045 pw.println(", last requested never");
2046 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002047 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002048
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002049 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002050 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002051
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002052 pw.println();
2053 mKeepaliveTracker.dump(pw);
2054
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002055 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002056 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002057
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002058 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002059 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002060 pw.println();
2061 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063 for(int i = 0; i < mInetLog.size(); i++) {
2064 pw.println(mInetLog.get(i));
2065 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002066 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002067 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002068
2069 if (argsContain(args, "--short") == false) {
2070 pw.println();
2071 synchronized (mValidationLogs) {
2072 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002073 for (ValidationLog p : mValidationLogs) {
2074 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002075 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002076 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002077 pw.decreaseIndent();
2078 }
2079 }
Erik Kline7523eb32015-07-09 18:24:03 +09002080
2081 pw.println();
2082 pw.println("mNetworkRequestInfoLogs (most recent first):");
2083 pw.increaseIndent();
2084 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2085 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002086
2087 pw.println();
2088 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2089 pw.increaseIndent();
2090 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2091 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002095 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002096 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002097 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002098 if (officialNai != null && officialNai.equals(nai)) return true;
2099 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002101 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002102 " - " + nai);
2103 }
2104 return false;
2105 }
2106
Robert Greenwalt42acef32009-08-12 16:08:25 -07002107 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002108 private class NetworkStateTrackerHandler extends Handler {
2109 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002110 super(looper);
2111 }
2112
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002113 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 default:
2116 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002117 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 handleAsyncChannelHalfConnect(msg);
2119 break;
2120 }
2121 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2122 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2123 if (nai != null) nai.asyncChannel.disconnect();
2124 break;
2125 }
2126 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2127 handleAsyncChannelDisconnected(msg);
2128 break;
2129 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002130 }
2131 return true;
2132 }
2133
2134 private void maybeHandleNetworkAgentMessage(Message msg) {
2135 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2136 if (nai == null) {
2137 if (VDBG) {
2138 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2139 log(String.format("%s from unknown NetworkAgent", what));
2140 }
2141 return;
2142 }
2143
2144 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2147 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002148 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2149 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002150 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002151 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002152 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002153 break;
2154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002156 if (VDBG) {
2157 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002158 "; created=" + nai.created +
2159 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002161 LinkProperties oldLp = nai.linkProperties;
2162 synchronized (nai) {
2163 nai.linkProperties = (LinkProperties)msg.obj;
2164 }
Robin Lee585e2482016-05-01 23:00:00 +01002165 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 break;
2167 }
2168 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002169 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 updateNetworkInfo(nai, info);
2171 break;
2172 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002173 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002174 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002175 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002176 break;
2177 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002178 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002179 try {
2180 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002181 } catch (Exception e) {
2182 // Never crash!
2183 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002184 }
2185 break;
2186 }
2187 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002188 try {
2189 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002190 } catch (Exception e) {
2191 // Never crash!
2192 loge("Exception in removeVpnUidRanges: " + e);
2193 }
2194 break;
2195 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002197 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2198 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002199 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002200 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002201 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002202 break;
2203 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002204 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002205 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2206 break;
2207 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002208 }
2209 }
2210
2211 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2212 switch (msg.what) {
2213 default:
2214 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002215 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002216 final NetworkAgentInfo nai;
2217 synchronized (mNetworkForNetId) {
2218 nai = mNetworkForNetId.get(msg.arg2);
2219 }
2220 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002221 final boolean valid =
2222 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002223 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002224 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2225 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002226 if (valid != nai.lastValidated) {
2227 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002228 nai.lastValidated = valid;
2229 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002230 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002231 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2232 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002233 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002234 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002235 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002236 Bundle redirectUrlBundle = new Bundle();
2237 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002238 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002239 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002240 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002241 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002242 if (wasValidated && !nai.lastValidated) {
2243 handleNetworkUnvalidated(nai);
2244 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002245 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 break;
2247 }
Paul Jensen869868be2014-05-15 10:33:05 -04002248 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002249 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002250 final boolean visible = (msg.arg1 != 0);
2251 final NetworkAgentInfo nai;
2252 synchronized (mNetworkForNetId) {
2253 nai = mNetworkForNetId.get(netId);
2254 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002255 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002256 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002257 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002258 nai.lastCaptivePortalDetected = visible;
2259 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002260 if (nai.lastCaptivePortalDetected &&
2261 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2262 if (DBG) log("Avoiding captive portal network: " + nai.name());
2263 nai.asyncChannel.sendMessage(
2264 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2265 teardownUnneededNetwork(nai);
2266 break;
2267 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002268 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002269 }
2270 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002271 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002272 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002273 if (nai == null) {
2274 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2275 break;
2276 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002277 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002278 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002279 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002280 }
Paul Jensen869868be2014-05-15 10:33:05 -04002281 }
Paul Jensen869868be2014-05-15 10:33:05 -04002282 break;
2283 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002284 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002285 return true;
2286 }
2287
Calvin On1f64f3f2016-10-11 15:10:46 -07002288 private int getCaptivePortalMode() {
2289 return Settings.Global.getInt(mContext.getContentResolver(),
2290 Settings.Global.CAPTIVE_PORTAL_MODE,
2291 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2292 }
2293
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2295 switch (msg.what) {
2296 default:
2297 return false;
2298 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2299 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2300 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2301 handleLingerComplete(nai);
2302 }
2303 break;
2304 }
2305 }
2306 return true;
2307 }
2308
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002309 @Override
2310 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002311 if (!maybeHandleAsyncChannelMessage(msg) &&
2312 !maybeHandleNetworkMonitorMessage(msg) &&
2313 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002314 maybeHandleNetworkAgentMessage(msg);
2315 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002316 }
2317 }
2318
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002319 private void updateLingerState(NetworkAgentInfo nai, long now) {
2320 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2321 // 2. If the network was lingering and there are now requests, unlinger it.
2322 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2323 // one lingered request, start lingering.
2324 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 if (DBG) log("Unlingering " + nai.name());
2327 nai.unlinger();
2328 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002329 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002331 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002332 nai.linger();
2333 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2334 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2335 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002336 }
2337
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 private void handleAsyncChannelHalfConnect(Message msg) {
2339 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002340 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2342 if (VDBG) log("NetworkFactory connected");
2343 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002345 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002347 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002348 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 } else {
2351 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002352 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2355 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2356 if (VDBG) log("NetworkAgent connected");
2357 // A network agent has requested a connection. Establish the connection.
2358 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2359 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2360 } else {
2361 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002362 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002363 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002365 synchronized (mNetworkForNetId) {
2366 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002367 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002368 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002369 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002370 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002371 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 }
2373 }
2374 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002375
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 private void handleAsyncChannelDisconnected(Message msg) {
2377 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2378 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002379 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002380 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002383 // TODO - if we move the logic to the network agent (have them disconnect
2384 // because they lost all their requests or because their score isn't good)
2385 // then they would disconnect organically, report their new state and then
2386 // disconnect the channel.
2387 if (nai.networkInfo.isConnected()) {
2388 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2389 null, null);
2390 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002391 final boolean wasDefault = isDefaultNetwork(nai);
2392 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002393 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002394 // Log default network disconnection before required book-keeping.
2395 // Let rematchAllNetworksAndRequests() below record a new default network event
2396 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2397 // whose timestamps tell how long it takes to recover a default network.
2398 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002399 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002400 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002401 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2402 // by other networks that are already connected. Perhaps that can be done by
2403 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2404 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002405 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002406 mKeepaliveTracker.handleStopAllKeepalives(nai,
2407 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002408 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002409 mNetworkAgentInfos.remove(msg.replyTo);
2410 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002411 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002412 // Remove the NetworkAgent, but don't mark the netId as
2413 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002414 mNetworkForNetId.remove(nai.network.netId);
2415 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002416 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002417 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2418 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002419 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2420 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2421 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002422 sendUpdatedScoreToFactories(request, 0);
2423 }
2424 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002425 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002426 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002428 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002429 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002430 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002431 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002432 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002433 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002434 if (nai.created) {
2435 // Tell netd to clean up the configuration for this network
2436 // (routing rules, DNS, etc).
2437 // This may be slow as it requires a lot of netd shelling out to ip and
2438 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2439 // after we've rematched networks with requests which should make a potential
2440 // fallback network the default or requested a new network from the
2441 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2442 // long time.
2443 try {
2444 mNetd.removeNetwork(nai.network.netId);
2445 } catch (Exception e) {
2446 loge("Exception removing network: " + e);
2447 }
2448 }
2449 synchronized (mNetworkForNetId) {
2450 mNetIdInUse.delete(nai.network.netId);
2451 }
2452 } else {
2453 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2454 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002455 }
2456 }
2457
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002458 // If this method proves to be too slow then we can maintain a separate
2459 // pendingIntent => NetworkRequestInfo map.
2460 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2461 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2462 Intent intent = pendingIntent.getIntent();
2463 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2464 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2465 if (existingPendingIntent != null &&
2466 existingPendingIntent.getIntent().filterEquals(intent)) {
2467 return entry.getValue();
2468 }
2469 }
2470 return null;
2471 }
2472
2473 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2474 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2475
2476 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2477 if (existingRequest != null) { // remove the existing request.
2478 if (DBG) log("Replacing " + existingRequest.request + " with "
2479 + nri.request + " because their intents matched.");
2480 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2481 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002482 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 }
2484
Erik Klineda4bfa82015-04-30 12:58:40 +09002485 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002486 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002487 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002488 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002489 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002490 if (nri.request.networkCapabilities.hasSignalStrength() &&
2491 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2492 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002493 }
2494 }
2495 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002496 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002497 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002498 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002499 }
2500 }
2501
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002502 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2503 int callingUid) {
2504 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2505 if (nri != null) {
2506 handleReleaseNetworkRequest(nri.request, callingUid);
2507 }
2508 }
2509
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002510 // Determines whether the network is the best (or could become the best, if it validated), for
2511 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2512 // on the value of reason:
2513 //
2514 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2515 // then it should be torn down.
2516 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2517 // then it should be lingered.
2518 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2519 final int numRequests;
2520 switch (reason) {
2521 case TEARDOWN:
2522 numRequests = nai.numRequestNetworkRequests();
2523 break;
2524 case LINGER:
2525 numRequests = nai.numForegroundNetworkRequests();
2526 break;
2527 default:
2528 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2529 return true;
2530 }
2531
2532 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002533 return false;
2534 }
Paul Jensene0988542015-06-25 15:30:08 -04002535 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002536 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2537 // Background requests don't affect lingering.
2538 continue;
2539 }
2540
Paul Jensene0988542015-06-25 15:30:08 -04002541 // If this Network is already the highest scoring Network for a request, or if
2542 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002543 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002544 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002545 // Note that this catches two important cases:
2546 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2547 // is currently satisfying the request. This is desirable when
2548 // cellular ends up validating but WiFi does not.
2549 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002550 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002551 // WiFi ends up validating and out scoring cellular.
2552 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2553 nai.getCurrentScoreAsValidated())) {
2554 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002555 }
2556 }
Paul Jensene0988542015-06-25 15:30:08 -04002557 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002558 }
2559
Erik Klineacdd6392016-07-07 16:50:58 +09002560 private NetworkRequestInfo getNriForAppRequest(
2561 NetworkRequest request, int callingUid, String requestedOperation) {
2562 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2563
Robert Greenwalt9258c642014-03-26 16:47:06 -07002564 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002565 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002566 log(String.format("UID %d attempted to %s for unowned request %s",
2567 callingUid, requestedOperation, nri));
2568 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002569 }
Erik Klineacdd6392016-07-07 16:50:58 +09002570 }
2571
2572 return nri;
2573 }
2574
2575 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2576 String description, int callbackType) {
2577 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2578 if (nri == null) return;
2579
2580 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2581 // The network that is satisfying this request may have changed since
2582 // the application requested the update.
2583 //
2584 // - If the request is no longer satisfied, don't send any updates.
2585 // - If the request is satisfied by a different network, it is the
2586 // caller's responsibility to check that the Network object in the
2587 // callback matches the network that was returned in the last
2588 // onAvailable() callback for this request.
2589 if (nai == null) return;
2590 callCallbackForRequest(nri, nai, callbackType, 0);
2591 }
2592
2593 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2594 handleRequestCallbackUpdate(request, callingUid,
2595 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2596 }
2597
2598 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2599 handleRequestCallbackUpdate(request, callingUid,
2600 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2601 }
2602
Erik Kline3841a482015-11-25 12:49:38 +09002603 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2604 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2605 nri.request.requestId) == null) {
2606 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2607 }
2608 }
2609
Erik Klineacdd6392016-07-07 16:50:58 +09002610 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2611 final NetworkRequestInfo nri = getNriForAppRequest(
2612 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002613 if (nri != null) {
2614 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2615 }
2616 }
Erik Klineacdd6392016-07-07 16:50:58 +09002617
Erik Kline3841a482015-11-25 12:49:38 +09002618 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2619 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2620 if (VDBG || (DBG && nri.request.isRequest())) {
2621 log("releasing " + nri.request + " (" + logCallbackType + ")");
2622 }
Erik Klineacdd6392016-07-07 16:50:58 +09002623 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002624 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002625 synchronized (mUidToNetworkRequestCount) {
2626 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2627 if (requests < 1) {
2628 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2629 nri.mUid);
2630 } else if (requests == 1) {
2631 mUidToNetworkRequestCount.removeAt(
2632 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2633 } else {
2634 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2635 }
2636 }
2637 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2638 if (nri.request.isRequest()) {
2639 boolean wasKept = false;
2640 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2641 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002642 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002643 nai.removeRequest(nri.request.requestId);
2644 if (VDBG) {
2645 log(" Removing from current network " + nai.name() +
2646 ", leaving " + nai.numNetworkRequests() + " requests.");
2647 }
2648 // If there are still lingered requests on this network, don't tear it down,
2649 // but resume lingering instead.
2650 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002651 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002652 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2653 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002654 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002655 wasKept = true;
2656 }
2657 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002658 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2659 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002660 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002661 }
Erik Klineacdd6392016-07-07 16:50:58 +09002662 }
2663
2664 // TODO: remove this code once we know that the Slog.wtf is never hit.
2665 //
2666 // Find all networks that are satisfying this request and remove the request
2667 // from their request lists.
2668 // TODO - it's my understanding that for a request there is only a single
2669 // network satisfying it, so this loop is wasteful
2670 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2671 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2672 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2673 otherNai.name() + ", but mNetworkAgentInfos says " +
2674 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002675 }
2676 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002677
Erik Klineacdd6392016-07-07 16:50:58 +09002678 // Maintain the illusion. When this request arrived, we might have pretended
2679 // that a network connected to serve it, even though the network was already
2680 // connected. Now that this request has gone away, we might have to pretend
2681 // that the network disconnected. LegacyTypeTracker will generate that
2682 // phantom disconnect for this type.
2683 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2684 boolean doRemove = true;
2685 if (wasKept) {
2686 // check if any of the remaining requests for this network are for the
2687 // same legacy type - if so, don't remove the nai
2688 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2689 NetworkRequest otherRequest = nai.requestAt(i);
2690 if (otherRequest.legacyType == nri.request.legacyType &&
2691 otherRequest.isRequest()) {
2692 if (DBG) log(" still have other legacy request - leaving");
2693 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002694 }
2695 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002696 }
2697
Erik Klineacdd6392016-07-07 16:50:58 +09002698 if (doRemove) {
2699 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002700 }
2701 }
Erik Klineacdd6392016-07-07 16:50:58 +09002702
2703 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2704 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2705 nri.request);
2706 }
2707 } else {
2708 // listens don't have a singular affectedNetwork. Check all networks to see
2709 // if this listen request applies and remove it.
2710 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2711 nai.removeRequest(nri.request.requestId);
2712 if (nri.request.networkCapabilities.hasSignalStrength() &&
2713 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2714 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2715 }
2716 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002717 }
Erik Kline3841a482015-11-25 12:49:38 +09002718 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002719 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002720
Lorenzo Colitti18660282016-07-04 12:55:44 +09002721 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2723 enforceConnectivityInternalPermission();
2724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2725 accept ? 1 : 0, always ? 1: 0, network));
2726 }
2727
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002728 @Override
2729 public void setAvoidUnvalidated(Network network) {
2730 enforceConnectivityInternalPermission();
2731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2732 }
2733
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002734 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2735 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2736 " accept=" + accept + " always=" + always);
2737
2738 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2739 if (nai == null) {
2740 // Nothing to do.
2741 return;
2742 }
2743
2744 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002745 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 return;
2747 }
2748
2749 if (!nai.networkMisc.explicitlySelected) {
2750 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2751 }
2752
2753 if (accept != nai.networkMisc.acceptUnvalidated) {
2754 int oldScore = nai.getCurrentScore();
2755 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002756 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002757 sendUpdatedScoreToFactories(nai);
2758 }
2759
2760 if (always) {
2761 nai.asyncChannel.sendMessage(
2762 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2763 }
2764
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002765 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002766 // Tell the NetworkAgent to not automatically reconnect to the network.
2767 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2768 // Teardown the nework.
2769 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002770 }
2771
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002772 }
2773
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002774 private void handleSetAvoidUnvalidated(Network network) {
2775 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2776 if (nai == null || nai.lastValidated) {
2777 // Nothing to do. The network either disconnected or revalidated.
2778 return;
2779 }
2780 if (!nai.avoidUnvalidated) {
2781 int oldScore = nai.getCurrentScore();
2782 nai.avoidUnvalidated = true;
2783 rematchAllNetworksAndRequests(nai, oldScore);
2784 sendUpdatedScoreToFactories(nai);
2785 }
2786 }
2787
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002788 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002789 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002790 mHandler.sendMessageDelayed(
2791 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2792 PROMPT_UNVALIDATED_DELAY_MS);
2793 }
2794
Hugo Benichic8e9e122016-09-14 23:23:08 +00002795 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002796 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002797 }
2798
Erik Kline065ab6e2016-10-02 18:02:14 +09002799 private void rematchForAvoidBadWifiUpdate() {
2800 rematchAllNetworksAndRequests(null, 0);
2801 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2802 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2803 sendUpdatedScoreToFactories(nai);
2804 }
2805 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002806 }
2807
Erik Kline065ab6e2016-10-02 18:02:14 +09002808 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002809 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002810 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002811 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002812 if (!configRestrict) {
2813 pw.println("Bad Wi-Fi avoidance: unrestricted");
2814 return;
2815 }
2816
2817 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2818 pw.increaseIndent();
2819 pw.println("Config restrict: " + configRestrict);
2820
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002821 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002822 String description;
2823 // Can't use a switch statement because strings are legal case labels, but null is not.
2824 if ("0".equals(value)) {
2825 description = "get stuck";
2826 } else if (value == null) {
2827 description = "prompt";
2828 } else if ("1".equals(value)) {
2829 description = "avoid";
2830 } else {
2831 description = value + " (?)";
2832 }
2833 pw.println("User setting: " + description);
2834 pw.println("Network overrides:");
2835 pw.increaseIndent();
2836 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2837 if (nai.avoidUnvalidated) {
2838 pw.println(nai.name());
2839 }
2840 }
2841 pw.decreaseIndent();
2842 pw.decreaseIndent();
2843 }
2844
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002845 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2846 final String action;
2847 switch (type) {
2848 case NO_INTERNET:
2849 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2850 break;
2851 case LOST_INTERNET:
2852 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2853 break;
2854 default:
2855 Slog.wtf(TAG, "Unknown notification type " + type);
2856 return;
2857 }
2858
2859 Intent intent = new Intent(action);
2860 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2861 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2862 intent.setClassName("com.android.settings",
2863 "com.android.settings.wifi.WifiNoInternetDialog");
2864
2865 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2866 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2867 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2868 }
2869
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002870 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002871 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002872 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2873
2874 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2875 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002876 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002877 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002878 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2879 return;
2880 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002881 showValidationNotification(nai, NotificationType.NO_INTERNET);
2882 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002883
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002884 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2885 NetworkCapabilities nc = nai.networkCapabilities;
2886 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002887
Erik Kline065ab6e2016-10-02 18:02:14 +09002888 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002889 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002890 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2891 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002892 }
2893
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002894 private class InternalHandler extends Handler {
2895 public InternalHandler(Looper looper) {
2896 super(looper);
2897 }
2898
2899 @Override
2900 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002901 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002902 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002903 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002904 String causedBy = null;
2905 synchronized (ConnectivityService.this) {
2906 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2907 mNetTransitionWakeLock.isHeld()) {
2908 mNetTransitionWakeLock.release();
2909 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002910 } else {
2911 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002912 }
2913 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002914 if (VDBG) {
2915 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2916 log("Failed to find a new network - expiring NetTransition Wakelock");
2917 } else {
2918 log("NetTransition Wakelock (" +
2919 (causedBy == null ? "unknown" : causedBy) +
2920 " cleared because we found a replacement network");
2921 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002922 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002923 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002924 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002925 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002926 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002927 break;
2928 }
Jason Monkdecd2952013-10-10 14:02:51 -04002929 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002930 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002931 break;
2932 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002933 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002934 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2935 break;
2936 }
2937 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2938 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002939 break;
2940 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002941 case EVENT_REGISTER_NETWORK_AGENT: {
2942 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2943 break;
2944 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002945 case EVENT_REGISTER_NETWORK_REQUEST:
2946 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002947 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002948 break;
2949 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002950 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2951 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002952 handleRegisterNetworkRequestWithIntent(msg);
2953 break;
2954 }
Erik Kline3841a482015-11-25 12:49:38 +09002955 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2956 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2957 handleTimedOutNetworkRequest(nri);
2958 break;
2959 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002960 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2961 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2962 break;
2963 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002964 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002965 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 break;
2967 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002968 case EVENT_SET_ACCEPT_UNVALIDATED: {
2969 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2970 break;
2971 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002972 case EVENT_SET_AVOID_UNVALIDATED: {
2973 handleSetAvoidUnvalidated((Network) msg.obj);
2974 break;
2975 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002976 case EVENT_PROMPT_UNVALIDATED: {
2977 handlePromptUnvalidated((Network) msg.obj);
2978 break;
2979 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002980 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2981 handleMobileDataAlwaysOn();
2982 break;
2983 }
Erik Klineacdd6392016-07-07 16:50:58 +09002984 case EVENT_REQUEST_LINKPROPERTIES:
2985 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2986 break;
2987 case EVENT_REQUEST_NETCAPABILITIES:
2988 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2989 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002990 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2991 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2992 mKeepaliveTracker.handleStartKeepalive(msg);
2993 break;
2994 }
2995 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2996 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2997 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2998 int slot = msg.arg1;
2999 int reason = msg.arg2;
3000 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3001 break;
3002 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003003 case EVENT_SYSTEM_READY: {
3004 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3005 nai.networkMonitor.systemReady = true;
3006 }
3007 break;
3008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 }
3010 }
3011 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003012
3013 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003014 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003015 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003016 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003017 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003018 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003019 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003020 } else {
3021 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3022 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003023 }
3024
3025 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003026 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003027 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003028 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003029
3030 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003031 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003032 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003033 } else {
3034 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3035 }
3036 }
3037
3038 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003039 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003040 public int getLastTetherError(String iface) {
3041 enforceTetherAccessPermission();
3042
3043 if (isTetheringSupported()) {
3044 return mTethering.getLastTetherError(iface);
3045 } else {
3046 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3047 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003048 }
3049
3050 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003051 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003052 public String[] getTetherableUsbRegexs() {
3053 enforceTetherAccessPermission();
3054 if (isTetheringSupported()) {
3055 return mTethering.getTetherableUsbRegexs();
3056 } else {
3057 return new String[0];
3058 }
3059 }
3060
Lorenzo Colitti18660282016-07-04 12:55:44 +09003061 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003062 public String[] getTetherableWifiRegexs() {
3063 enforceTetherAccessPermission();
3064 if (isTetheringSupported()) {
3065 return mTethering.getTetherableWifiRegexs();
3066 } else {
3067 return new String[0];
3068 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003069 }
3070
Lorenzo Colitti18660282016-07-04 12:55:44 +09003071 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003072 public String[] getTetherableBluetoothRegexs() {
3073 enforceTetherAccessPermission();
3074 if (isTetheringSupported()) {
3075 return mTethering.getTetherableBluetoothRegexs();
3076 } else {
3077 return new String[0];
3078 }
3079 }
3080
Lorenzo Colitti18660282016-07-04 12:55:44 +09003081 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003082 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003083 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003084 if (isTetheringSupported()) {
3085 return mTethering.setUsbTethering(enable);
3086 } else {
3087 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3088 }
3089 }
3090
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003091 // TODO - move iface listing, queries, etc to new module
3092 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003093 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003094 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003095 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003096 return mTethering.getTetherableIfaces();
3097 }
3098
Lorenzo Colitti18660282016-07-04 12:55:44 +09003099 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003100 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003101 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003102 return mTethering.getTetheredIfaces();
3103 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003104
Lorenzo Colitti18660282016-07-04 12:55:44 +09003105 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003106 public String[] getTetheringErroredIfaces() {
3107 enforceTetherAccessPermission();
3108 return mTethering.getErroredIfaces();
3109 }
3110
Lorenzo Colitti18660282016-07-04 12:55:44 +09003111 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003112 public String[] getTetheredDhcpRanges() {
3113 enforceConnectivityInternalPermission();
3114 return mTethering.getTetheredDhcpRanges();
3115 }
3116
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003117 // if ro.tether.denied = true we default to no tethering
3118 // gservices could set the secure setting to 1 though to enable it on a build where it
3119 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003120 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003121 public boolean isTetheringSupported() {
3122 enforceTetherAccessPermission();
3123 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003124 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003125 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3126 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003127 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
Erik Klined781fba2017-01-23 13:01:58 +09003128 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003129 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003130
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003131 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003132 public void startTethering(int type, ResultReceiver receiver,
3133 boolean showProvisioningUi) {
3134 ConnectivityManager.enforceTetherChangePermission(mContext);
3135 if (!isTetheringSupported()) {
3136 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3137 return;
3138 }
3139 mTethering.startTethering(type, receiver, showProvisioningUi);
3140 }
3141
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003142 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003143 public void stopTethering(int type) {
3144 ConnectivityManager.enforceTetherChangePermission(mContext);
3145 mTethering.stopTethering(type);
3146 }
3147
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003148 // Called when we lose the default network and have no replacement yet.
3149 // This will automatically be cleared after X seconds or a new default network
3150 // becomes CONNECTED, whichever happens first. The timer is started by the
3151 // first caller and not restarted by subsequent callers.
3152 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003153 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003154 synchronized (this) {
3155 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003156 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003157 mNetTransitionWakeLock.acquire();
3158 mNetTransitionWakeLockCausedBy = forWhom;
3159 }
3160 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003161 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003162 mNetTransitionWakeLockTimeout);
3163 return;
3164 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003165
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003166 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003167 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003168 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003169 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003170 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003171 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003172 }
3173
Lorenzo Colitti18660282016-07-04 12:55:44 +09003174 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003175 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003176 enforceAccessPermission();
3177 enforceInternetPermission();
3178
Paul Jensenbfd17b72015-04-07 12:43:13 -04003179 NetworkAgentInfo nai;
3180 if (network == null) {
3181 nai = getDefaultNetwork();
3182 } else {
3183 nai = getNetworkAgentInfoForNetwork(network);
3184 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003185 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3186 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3187 return;
3188 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003189 // Revalidate if the app report does not match our current validated state.
3190 if (hasConnectivity == nai.lastValidated) return;
3191 final int uid = Binder.getCallingUid();
3192 if (DBG) {
3193 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3194 ") by " + uid);
3195 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003196 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003197 // Validating a network that has not yet connected could result in a call to
3198 // rematchNetworkAndRequests() which is not meant to work on such networks.
3199 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003200
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003201 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003202
3203 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3204 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003205 }
3206
Paul Jensencee9b512015-05-06 07:32:40 -04003207 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003208 // this information is already available as a world read/writable jvm property
3209 // so this API change wouldn't have a benifit. It also breaks the passing
3210 // of proxy info to all the JVMs.
3211 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003212 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003213 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003214 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3215 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003216 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003217 }
3218
Lorenzo Colitti18660282016-07-04 12:55:44 +09003219 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003220 public ProxyInfo getProxyForNetwork(Network network) {
3221 if (network == null) return getDefaultProxy();
3222 final ProxyInfo globalProxy = getGlobalProxy();
3223 if (globalProxy != null) return globalProxy;
3224 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3225 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3226 // caller may not have.
3227 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3228 if (nai == null) return null;
3229 synchronized (nai) {
3230 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3231 if (proxyInfo == null) return null;
3232 return new ProxyInfo(proxyInfo);
3233 }
3234 }
3235
Paul Jensene0bef712014-12-10 15:12:18 -05003236 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3237 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3238 // proxy is null then there is no proxy in place).
3239 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3240 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3241 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3242 proxy = null;
3243 }
3244 return proxy;
3245 }
3246
3247 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3248 // better for determining if a new proxy broadcast is necessary:
3249 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3250 // avoid unnecessary broadcasts.
3251 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3252 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3253 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3254 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3255 // all set.
3256 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3257 a = canonicalizeProxyInfo(a);
3258 b = canonicalizeProxyInfo(b);
3259 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3260 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3261 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3262 }
3263
Jason Monk207900c2014-04-25 15:00:09 -04003264 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003265 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003266
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003267 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 if (proxyProperties == mGlobalProxy) return;
3269 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3270 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3271
3272 String host = "";
3273 int port = 0;
3274 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003275 String pacFileUrl = "";
3276 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003277 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003278 if (!proxyProperties.isValid()) {
3279 if (DBG)
3280 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3281 return;
3282 }
Jason Monk207900c2014-04-25 15:00:09 -04003283 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003284 host = mGlobalProxy.getHost();
3285 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003286 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003287 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003288 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003289 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 } else {
3291 mGlobalProxy = null;
3292 }
3293 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003294 final long token = Binder.clearCallingIdentity();
3295 try {
3296 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3297 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3298 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3299 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003300 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003301 } finally {
3302 Binder.restoreCallingIdentity(token);
3303 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003304
Jason Monkcf0f97a2014-10-02 15:39:38 -04003305 if (mGlobalProxy == null) {
3306 proxyProperties = mDefaultProxy;
3307 }
3308 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003309 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310 }
3311
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003312 private void loadGlobalProxy() {
3313 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003314 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3315 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3316 String exclList = Settings.Global.getString(res,
3317 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003318 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3319 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003320 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003321 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003322 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003323 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003324 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003325 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003326 if (!proxyProperties.isValid()) {
3327 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3328 return;
3329 }
3330
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003331 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003332 mGlobalProxy = proxyProperties;
3333 }
3334 }
3335 }
3336
Jason Monk207900c2014-04-25 15:00:09 -04003337 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003338 // this information is already available as a world read/writable jvm property
3339 // so this API change wouldn't have a benifit. It also breaks the passing
3340 // of proxy info to all the JVMs.
3341 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003342 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 return mGlobalProxy;
3344 }
3345 }
3346
Jason Monk207900c2014-04-25 15:00:09 -04003347 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003348 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003349 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003350 proxy = null;
3351 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003352 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003353 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003354 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003355 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003356 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3357 return;
3358 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003359
3360 // This call could be coming from the PacManager, containing the port of the local
3361 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3362 // global (to get the correct local port), and send a broadcast.
3363 // TODO: Switch PacManager to have its own message to send back rather than
3364 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003365 if ((mGlobalProxy != null) && (proxy != null)
3366 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003367 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3368 mGlobalProxy = proxy;
3369 sendProxyBroadcast(mGlobalProxy);
3370 return;
3371 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003372 mDefaultProxy = proxy;
3373
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003374 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003375 if (!mDefaultProxyDisabled) {
3376 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003377 }
3378 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003379 }
3380
Paul Jensene0bef712014-12-10 15:12:18 -05003381 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3382 // This method gets called when any network changes proxy, but the broadcast only ever contains
3383 // the default proxy (even if it hasn't changed).
3384 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3385 // world where an app might be bound to a non-default network.
3386 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3387 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3388 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3389
3390 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3391 sendProxyBroadcast(getDefaultProxy());
3392 }
3393 }
3394
Robert Greenwalt434203a2010-10-11 16:00:27 -07003395 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003396 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3397 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003398 if (!TextUtils.isEmpty(proxy)) {
3399 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003400 if (data.length == 0) {
3401 return;
3402 }
3403
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 String proxyHost = data[0];
3405 int proxyPort = 8080;
3406 if (data.length > 1) {
3407 try {
3408 proxyPort = Integer.parseInt(data[1]);
3409 } catch (NumberFormatException e) {
3410 return;
3411 }
3412 }
Jason Monk207900c2014-04-25 15:00:09 -04003413 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003414 setGlobalProxy(p);
3415 }
3416 }
3417
Jason Monk207900c2014-04-25 15:00:09 -04003418 private void sendProxyBroadcast(ProxyInfo proxy) {
3419 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003420 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003421 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003422 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003423 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3424 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003425 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003426 final long ident = Binder.clearCallingIdentity();
3427 try {
3428 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003432 }
3433
3434 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003435 final private HashMap<Uri, Integer> mUriEventMap;
3436 final private Context mContext;
3437 final private Handler mHandler;
3438
3439 SettingsObserver(Context context, Handler handler) {
3440 super(null);
3441 mUriEventMap = new HashMap<Uri, Integer>();
3442 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003443 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 }
3445
Erik Klineda4bfa82015-04-30 12:58:40 +09003446 void observe(Uri uri, int what) {
3447 mUriEventMap.put(uri, what);
3448 final ContentResolver resolver = mContext.getContentResolver();
3449 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003450 }
3451
3452 @Override
3453 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003454 Slog.wtf(TAG, "Should never be reached.");
3455 }
3456
3457 @Override
3458 public void onChange(boolean selfChange, Uri uri) {
3459 final Integer what = mUriEventMap.get(uri);
3460 if (what != null) {
3461 mHandler.obtainMessage(what.intValue()).sendToTarget();
3462 } else {
3463 loge("No matching event to send for URI=" + uri);
3464 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 }
3466 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003467
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003468 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003469 Slog.d(TAG, s);
3470 }
3471
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003472 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003473 Slog.e(TAG, s);
3474 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003475
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003476 private static <T> T checkNotNull(T value, String message) {
3477 if (value == null) {
3478 throw new NullPointerException(message);
3479 }
3480 return value;
3481 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003482
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003483 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003484 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003485 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3486 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3487 *
3488 * @param oldPackage Package name of the application which currently controls VPN, which will
3489 * be replaced. If there is no such application, this should should either be
3490 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3491 * @param newPackage Package name of the application which should gain control of VPN, or
3492 * {@code null} to disable.
3493 * @param userId User for whom to prepare the new VPN.
3494 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003495 * @hide
3496 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003497 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003498 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3499 int userId) {
3500 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003501 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003502
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003503 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003504 Vpn vpn = mVpns.get(userId);
3505 if (vpn != null) {
3506 return vpn.prepare(oldPackage, newPackage);
3507 } else {
3508 return false;
3509 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003510 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003511 }
3512
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003513 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003514 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3515 * This method is used by system-privileged apps.
3516 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3517 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3518 *
3519 * @param packageName The package for which authorization state should change.
3520 * @param userId User for whom {@code packageName} is installed.
3521 * @param authorized {@code true} if this app should be able to start a VPN connection without
3522 * explicit user approval, {@code false} if not.
3523 *
Jeff Davidson05542602014-08-11 14:07:27 -07003524 * @hide
3525 */
3526 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003527 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3528 enforceCrossUserPermission(userId);
3529
Jeff Davidson05542602014-08-11 14:07:27 -07003530 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003531 Vpn vpn = mVpns.get(userId);
3532 if (vpn != null) {
3533 vpn.setPackageAuthorization(packageName, authorized);
3534 }
Jeff Davidson05542602014-08-11 14:07:27 -07003535 }
3536 }
3537
3538 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003539 * Configure a TUN interface and return its file descriptor. Parameters
3540 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003541 * and not available in ConnectivityManager. Permissions are checked in
3542 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003543 * @hide
3544 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003545 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003546 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003547 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003548 int user = UserHandle.getUserId(Binder.getCallingUid());
3549 synchronized(mVpns) {
3550 return mVpns.get(user).establish(config);
3551 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003552 }
3553
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003554 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003555 * Start legacy VPN, controlling native daemons as needed. Creates a
3556 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003557 */
3558 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003559 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003560 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003561 final LinkProperties egress = getActiveLinkProperties();
3562 if (egress == null) {
3563 throw new IllegalStateException("Missing active network connection");
3564 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003565 int user = UserHandle.getUserId(Binder.getCallingUid());
3566 synchronized(mVpns) {
3567 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3568 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003569 }
3570
3571 /**
3572 * Return the information of the ongoing legacy VPN. This method is used
3573 * by VpnSettings and not available in ConnectivityManager. Permissions
3574 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003575 */
3576 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003577 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3578 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003579
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003580 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003581 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003582 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003583 }
3584
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003585 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003586 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3587 * and not available in ConnectivityManager.
3588 */
3589 @Override
3590 public VpnInfo[] getAllVpnInfo() {
3591 enforceConnectivityInternalPermission();
3592 if (mLockdownEnabled) {
3593 return new VpnInfo[0];
3594 }
3595
3596 synchronized(mVpns) {
3597 List<VpnInfo> infoList = new ArrayList<>();
3598 for (int i = 0; i < mVpns.size(); i++) {
3599 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3600 if (info != null) {
3601 infoList.add(info);
3602 }
3603 }
3604 return infoList.toArray(new VpnInfo[infoList.size()]);
3605 }
3606 }
3607
3608 /**
3609 * @return VPN information for accounting, or null if we can't retrieve all required
3610 * information, e.g primary underlying iface.
3611 */
3612 @Nullable
3613 private VpnInfo createVpnInfo(Vpn vpn) {
3614 VpnInfo info = vpn.getVpnInfo();
3615 if (info == null) {
3616 return null;
3617 }
3618 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3619 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3620 // the underlyingNetworks list.
3621 if (underlyingNetworks == null) {
3622 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3623 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3624 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3625 }
3626 } else if (underlyingNetworks.length > 0) {
3627 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3628 if (linkProperties != null) {
3629 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3630 }
3631 }
3632 return info.primaryUnderlyingIface == null ? null : info;
3633 }
3634
3635 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003636 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3637 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003638 * Permissions are checked in Vpn class.
3639 * @hide
3640 */
3641 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003642 public VpnConfig getVpnConfig(int userId) {
3643 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003644 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003645 Vpn vpn = mVpns.get(userId);
3646 if (vpn != null) {
3647 return vpn.getVpnConfig();
3648 } else {
3649 return null;
3650 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003651 }
3652 }
3653
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003654 @Override
3655 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003656 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3657 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3658 return false;
3659 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003660
3661 // Tear down existing lockdown if profile was removed
3662 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3663 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003664 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3665 if (profileTag == null) {
3666 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3667 return false;
3668 }
3669 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003670 final VpnProfile profile = VpnProfile.decode(
3671 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003672 if (profile == null) {
3673 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3674 setLockdownTracker(null);
3675 return true;
3676 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003677 int user = UserHandle.getUserId(Binder.getCallingUid());
3678 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003679 Vpn vpn = mVpns.get(user);
3680 if (vpn == null) {
3681 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3682 return false;
3683 }
3684 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003685 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003686 } else {
3687 setLockdownTracker(null);
3688 }
3689
3690 return true;
3691 }
3692
3693 /**
3694 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3695 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3696 */
3697 private void setLockdownTracker(LockdownVpnTracker tracker) {
3698 // Shutdown any existing tracker
3699 final LockdownVpnTracker existing = mLockdownTracker;
3700 mLockdownTracker = null;
3701 if (existing != null) {
3702 existing.shutdown();
3703 }
3704
Robin Leec3736bc2017-03-10 16:19:54 +00003705 if (tracker != null) {
3706 mLockdownTracker = tracker;
3707 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003708 }
3709 }
3710
3711 private void throwIfLockdownEnabled() {
3712 if (mLockdownEnabled) {
3713 throw new IllegalStateException("Unavailable in lockdown mode");
3714 }
3715 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003716
Robin Lee244ce8e2016-01-05 18:03:46 +00003717 /**
Robin Lee17e61832016-05-09 13:46:28 +01003718 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3719 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003720 *
Robin Lee17e61832016-05-09 13:46:28 +01003721 * @return {@code true} if the service was started, the service was already connected, or there
3722 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003723 */
Robin Lee17e61832016-05-09 13:46:28 +01003724 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003725 synchronized (mVpns) {
3726 Vpn vpn = mVpns.get(userId);
3727 if (vpn == null) {
3728 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3729 // exists already.
3730 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3731 return false;
3732 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003733
Robin Lee812800c2016-05-13 15:38:08 +01003734 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003735 }
3736 }
3737
3738 @Override
Robin Leedc679712016-05-03 13:23:03 +01003739 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003740 enforceConnectivityInternalPermission();
3741 enforceCrossUserPermission(userId);
3742
3743 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3744 if (LockdownVpnTracker.isEnabled()) {
3745 return false;
3746 }
3747
Robin Lee244ce8e2016-01-05 18:03:46 +00003748 synchronized (mVpns) {
3749 Vpn vpn = mVpns.get(userId);
3750 if (vpn == null) {
3751 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3752 return false;
3753 }
Robin Lee17e61832016-05-09 13:46:28 +01003754 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003755 return false;
3756 }
Robin Lee17e61832016-05-09 13:46:28 +01003757 if (!startAlwaysOnVpn(userId)) {
3758 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003759 return false;
3760 }
3761 }
3762 return true;
3763 }
3764
3765 @Override
3766 public String getAlwaysOnVpnPackage(int userId) {
3767 enforceConnectivityInternalPermission();
3768 enforceCrossUserPermission(userId);
3769
3770 synchronized (mVpns) {
3771 Vpn vpn = mVpns.get(userId);
3772 if (vpn == null) {
3773 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3774 return null;
3775 }
3776 return vpn.getAlwaysOnPackage();
3777 }
3778 }
3779
Wink Savilleab9321d2013-06-29 21:10:57 -07003780 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003781 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003782 // TODO: Remove? Any reason to trigger a provisioning check?
3783 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003784 }
3785
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003786 /** Location to an updatable file listing carrier provisioning urls.
3787 * An example:
3788 *
3789 * <?xml version="1.0" encoding="utf-8"?>
3790 * <provisioningUrls>
3791 * <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 -07003792 * </provisioningUrls>
3793 */
3794 private static final String PROVISIONING_URL_PATH =
3795 "/data/misc/radio/provisioning_urls.xml";
3796 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003797
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003798 /** XML tag for root element. */
3799 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3800 /** XML tag for individual url */
3801 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003802 /** XML attribute for mcc */
3803 private static final String ATTR_MCC = "mcc";
3804 /** XML attribute for mnc */
3805 private static final String ATTR_MNC = "mnc";
3806
Paul Jensen434dde82015-06-11 09:43:30 -04003807 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003808 FileReader fileReader = null;
3809 XmlPullParser parser = null;
3810 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811
3812 try {
3813 fileReader = new FileReader(mProvisioningUrlFile);
3814 parser = Xml.newPullParser();
3815 parser.setInput(fileReader);
3816 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3817
3818 while (true) {
3819 XmlUtils.nextElement(parser);
3820
3821 String element = parser.getName();
3822 if (element == null) break;
3823
Paul Jensen434dde82015-06-11 09:43:30 -04003824 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003825 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3826 try {
3827 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3828 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3829 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3830 parser.next();
3831 if (parser.getEventType() == XmlPullParser.TEXT) {
3832 return parser.getText();
3833 }
3834 }
3835 }
3836 } catch (NumberFormatException e) {
3837 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3838 }
3839 }
3840 }
3841 return null;
3842 } catch (FileNotFoundException e) {
3843 loge("Carrier Provisioning Urls file not found");
3844 } catch (XmlPullParserException e) {
3845 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3846 } catch (IOException e) {
3847 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3848 } finally {
3849 if (fileReader != null) {
3850 try {
3851 fileReader.close();
3852 } catch (IOException e) {}
3853 }
3854 }
3855 return null;
3856 }
3857
Wink Saville42d4f082013-07-20 20:31:59 -07003858 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003859 public String getMobileProvisioningUrl() {
3860 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003861 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003862 if (TextUtils.isEmpty(url)) {
3863 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003864 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003865 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003866 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003867 }
Wink Saville8cf35602013-07-10 23:00:07 -07003868 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003869 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003870 String phoneNumber = mTelephonyManager.getLine1Number();
3871 if (TextUtils.isEmpty(phoneNumber)) {
3872 phoneNumber = "0000000000";
3873 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003874 url = String.format(url,
3875 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3876 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003877 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003878 }
3879
Wink Savilleab9321d2013-06-29 21:10:57 -07003880 return url;
3881 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003882
Wink Saville948282b2013-08-29 08:55:16 -07003883 @Override
3884 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003885 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003886 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003887 final long ident = Binder.clearCallingIdentity();
3888 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003889 // Concatenate the range of types onto the range of NetIDs.
3890 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3891 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003892 } finally {
3893 Binder.restoreCallingIdentity(ident);
3894 }
Wink Saville948282b2013-08-29 08:55:16 -07003895 }
Wink Saville7788c612013-08-29 14:57:08 -07003896
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003897 @Override
3898 public void setAirplaneMode(boolean enable) {
3899 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003900 final long ident = Binder.clearCallingIdentity();
3901 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003902 final ContentResolver cr = mContext.getContentResolver();
3903 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3904 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3905 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003906 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003907 } finally {
3908 Binder.restoreCallingIdentity(ident);
3909 }
3910 }
3911
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003912 private void onUserStart(int userId) {
3913 synchronized(mVpns) {
3914 Vpn userVpn = mVpns.get(userId);
3915 if (userVpn != null) {
3916 loge("Starting user already has a VPN");
3917 return;
3918 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003919 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003920 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003921 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003922 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3923 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003924 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003925 }
3926
3927 private void onUserStop(int userId) {
3928 synchronized(mVpns) {
3929 Vpn userVpn = mVpns.get(userId);
3930 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003931 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003932 return;
3933 }
Robin Lee17e61832016-05-09 13:46:28 +01003934 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003935 mVpns.delete(userId);
3936 }
3937 }
3938
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003939 private void onUserAdded(int userId) {
3940 synchronized(mVpns) {
3941 final int vpnsSize = mVpns.size();
3942 for (int i = 0; i < vpnsSize; i++) {
3943 Vpn vpn = mVpns.valueAt(i);
3944 vpn.onUserAdded(userId);
3945 }
3946 }
3947 }
3948
3949 private void onUserRemoved(int userId) {
3950 synchronized(mVpns) {
3951 final int vpnsSize = mVpns.size();
3952 for (int i = 0; i < vpnsSize; i++) {
3953 Vpn vpn = mVpns.valueAt(i);
3954 vpn.onUserRemoved(userId);
3955 }
3956 }
3957 }
3958
Robin Lee89e7a692016-02-29 14:38:17 +00003959 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003960 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3961 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3962 updateLockdownVpn();
3963 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003964 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003965 }
3966 }
3967
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3969 @Override
3970 public void onReceive(Context context, Intent intent) {
3971 final String action = intent.getAction();
3972 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3973 if (userId == UserHandle.USER_NULL) return;
3974
Robin Lee323f29d2016-05-04 16:38:06 +01003975 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003976 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003977 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003978 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003979 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3980 onUserAdded(userId);
3981 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3982 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003983 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3984 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003985 }
3986 }
3987 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003988
Robert Greenwalta67be032014-05-16 15:49:14 -07003989 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3990 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3992 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003993
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003994 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3995 // Map from UID to number of NetworkRequests that UID has filed.
3996 @GuardedBy("mUidToNetworkRequestCount")
3997 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3998
Robert Greenwalta67be032014-05-16 15:49:14 -07003999 private static class NetworkFactoryInfo {
4000 public final String name;
4001 public final Messenger messenger;
4002 public final AsyncChannel asyncChannel;
4003
4004 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4005 this.name = name;
4006 this.messenger = messenger;
4007 this.asyncChannel = asyncChannel;
4008 }
4009 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004010
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004011 private void ensureNetworkRequestHasType(NetworkRequest request) {
4012 if (request.type == NetworkRequest.Type.NONE) {
4013 throw new IllegalArgumentException(
4014 "All NetworkRequests in ConnectivityService must have a type");
4015 }
4016 }
4017
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004018 /**
4019 * Tracks info about the requester.
4020 * Also used to notice when the calling process dies so we can self-expire
4021 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004025 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 final int mPid;
4028 final int mUid;
4029 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004031 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004032 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004033 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004034 mPendingIntent = pi;
4035 messenger = null;
4036 mBinder = null;
4037 mPid = getCallingPid();
4038 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004039 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004040 }
4041
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004042 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 super();
4044 messenger = m;
4045 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004046 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 mBinder = binder;
4048 mPid = getCallingPid();
4049 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004051 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004052
4053 try {
4054 mBinder.linkToDeath(this, 0);
4055 } catch (RemoteException e) {
4056 binderDied();
4057 }
4058 }
4059
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004060 private void enforceRequestCountLimit() {
4061 synchronized (mUidToNetworkRequestCount) {
4062 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4063 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4064 throw new IllegalArgumentException("Too many NetworkRequests filed");
4065 }
4066 mUidToNetworkRequestCount.put(mUid, networkRequests);
4067 }
4068 }
4069
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004071 if (mBinder != null) {
4072 mBinder.unlinkToDeath(this, 0);
4073 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 }
4075
4076 public void binderDied() {
4077 log("ConnectivityService NetworkRequestInfo binderDied(" +
4078 request + ", " + mBinder + ")");
4079 releaseNetworkRequest(request);
4080 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004081
4082 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004083 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 }
4087
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004088 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4089 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4090 if (badCapability != null) {
4091 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004092 }
4093 }
4094
Erik Kline9d598e12015-07-13 16:37:51 +09004095 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004096 final SortedSet<Integer> thresholds = new TreeSet();
4097 synchronized (nai) {
4098 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4099 if (nri.request.networkCapabilities.hasSignalStrength() &&
4100 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4101 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4102 }
4103 }
4104 }
Erik Kline9d598e12015-07-13 16:37:51 +09004105 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004106 }
4107
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004108 private void updateSignalStrengthThresholds(
4109 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4110 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004111 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004112 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4113
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004114 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004115 String detail;
4116 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4117 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4118 } else {
4119 detail = reason;
4120 }
4121 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4122 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4123 }
4124
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004125 nai.asyncChannel.sendMessage(
4126 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004127 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004128 }
4129
Robert Greenwalt9258c642014-03-26 16:47:06 -07004130 @Override
4131 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004132 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004133 final NetworkRequest.Type type = (networkCapabilities == null)
4134 ? NetworkRequest.Type.TRACK_DEFAULT
4135 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004136 // If the requested networkCapabilities is null, take them instead from
4137 // the default network request. This allows callers to keep track of
4138 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004139 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004140 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4141 enforceAccessPermission();
4142 } else {
4143 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4144 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004145 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4146 // of the app when the request is filed, but we never change the request if the app
4147 // changes network state. http://b/29964605
4148 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004149 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004150 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004151
Etan Cohenba07c8c2017-02-05 10:42:27 -08004152 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153 throw new IllegalArgumentException("Bad timeout specified");
4154 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155
Etan Cohenddb9ef02015-11-18 10:56:15 -08004156 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4157 .equals(networkCapabilities.getNetworkSpecifier())) {
4158 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4159 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4160 }
4161
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004162 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004163 nextNetworkRequestId(), type);
4164 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004165 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166
4167 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004168 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004170 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 }
4172 return networkRequest;
4173 }
4174
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004175 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004176 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004177 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 } else {
4179 enforceChangePermission();
4180 }
4181 }
4182
fenglub15e72b2015-03-20 11:29:56 -07004183 @Override
fengludb571472015-04-21 17:12:05 -07004184 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004185 enforceAccessPermission();
4186 NetworkAgentInfo nai = null;
4187 if (network == null) {
4188 return false;
4189 }
4190 synchronized (mNetworkForNetId) {
4191 nai = mNetworkForNetId.get(network.netId);
4192 }
4193 if (nai != null) {
4194 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4195 return true;
4196 }
4197 return false;
4198 }
4199
Felipe Lemeee27cab2016-06-20 16:36:29 -07004200 private boolean isSystem(int uid) {
4201 return uid < Process.FIRST_APPLICATION_UID;
4202 }
fenglub15e72b2015-03-20 11:29:56 -07004203
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004205 final int uid = Binder.getCallingUid();
4206 if (isSystem(uid)) {
4207 return;
4208 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004210 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004211 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004212 synchronized(mRulesLock) {
4213 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4214 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004215 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4216 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004218 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004219 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 }
4221 }
4222 }
4223
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 @Override
4225 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4226 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 checkNotNull(operation, "PendingIntent cannot be null.");
4228 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4229 enforceNetworkRequestPermissions(networkCapabilities);
4230 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004231 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232
4233 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004234 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4235 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004236 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004237 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4238 nri));
4239 return networkRequest;
4240 }
4241
Jeremy Joslin79294842014-12-03 17:15:28 -08004242 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4243 mHandler.sendMessageDelayed(
4244 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4245 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4246 }
4247
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004248 @Override
4249 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004250 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4252 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 }
4254
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004255 // In order to implement the compatibility measure for pre-M apps that call
4256 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4257 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4258 // This ensures it has permission to do so.
4259 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4260 if (nc == null) {
4261 return false;
4262 }
4263 int[] transportTypes = nc.getTransportTypes();
4264 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4265 return false;
4266 }
4267 try {
4268 mContext.enforceCallingOrSelfPermission(
4269 android.Manifest.permission.ACCESS_WIFI_STATE,
4270 "ConnectivityService");
4271 } catch (SecurityException e) {
4272 return false;
4273 }
4274 return true;
4275 }
4276
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 @Override
4278 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4279 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004280 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4281 enforceAccessPermission();
4282 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004283
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004284 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4285 if (!ConnectivityManager.checkChangePermission(mContext)) {
4286 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4287 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4288 // onLost and onAvailable callbacks when networks move in and out of the background.
4289 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4290 // can't request networks.
4291 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4292 }
4293
4294 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004295 NetworkRequest.Type.LISTEN);
4296 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004297 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298
4299 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4300 return networkRequest;
4301 }
4302
4303 @Override
4304 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4305 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004306 checkNotNull(operation, "PendingIntent cannot be null.");
4307 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4308 enforceAccessPermission();
4309 }
4310
Erik Kline7523eb32015-07-09 18:24:03 +09004311 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004312 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4313 NetworkRequest.Type.LISTEN);
4314 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004315 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004316
4317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318 }
4319
4320 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004321 public void requestLinkProperties(NetworkRequest networkRequest) {
4322 ensureNetworkRequestHasType(networkRequest);
4323 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4324 mHandler.sendMessage(mHandler.obtainMessage(
4325 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4326 }
4327
4328 @Override
4329 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4330 ensureNetworkRequestHasType(networkRequest);
4331 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4332 mHandler.sendMessage(mHandler.obtainMessage(
4333 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4334 }
4335
4336 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004337 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004338 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004339 mHandler.sendMessage(mHandler.obtainMessage(
4340 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004341 }
4342
4343 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004344 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004345 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004346 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4347 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004348 }
4349
Robert Greenwalta67be032014-05-16 15:49:14 -07004350 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004351 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004352 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4353 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4354 }
4355
4356 @Override
4357 public void unregisterNetworkFactory(Messenger messenger) {
4358 enforceConnectivityInternalPermission();
4359 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4360 }
4361
4362 private void handleUnregisterNetworkFactory(Messenger messenger) {
4363 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4364 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004365 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004366 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004367 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004368 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004369 }
4370
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 /**
4372 * NetworkAgentInfo supporting a request by requestId.
4373 * These have already been vetted (their Capabilities satisfy the request)
4374 * and the are the highest scored network available.
4375 * the are keyed off the Requests requestId.
4376 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004377 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4379 new SparseArray<NetworkAgentInfo>();
4380
Paul Jensen31a94f42015-02-13 14:18:39 -05004381 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4382 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4384 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004385 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4386 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4387 // there may not be a strict 1:1 correlation between the two.
4388 @GuardedBy("mNetworkForNetId")
4389 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 // NetworkAgentInfo keyed off its connecting messenger
4392 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004393 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4395 new HashMap<Messenger, NetworkAgentInfo>();
4396
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004397 @GuardedBy("mBlockedAppUids")
4398 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4399
Paul Jensen2c311d62014-11-17 12:34:51 -05004400 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 private final NetworkRequest mDefaultRequest;
4402
Erik Klineda4bfa82015-04-30 12:58:40 +09004403 // Request used to optionally keep mobile data active even when higher
4404 // priority networks like Wi-Fi are active.
4405 private final NetworkRequest mDefaultMobileDataRequest;
4406
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004407 private NetworkAgentInfo getDefaultNetwork() {
4408 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4409 }
4410
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004411 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004412 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004413 }
4414
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004415 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4416 return nri.request.requestId == mDefaultRequest.requestId;
4417 }
4418
Paul Jensen31a94f42015-02-13 14:18:39 -05004419 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004421 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 enforceConnectivityInternalPermission();
4423
Paul Jensen2c311d62014-11-17 12:34:51 -05004424 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4425 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004426 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004427 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4428 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004429 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004430 synchronized (this) {
4431 nai.networkMonitor.systemReady = mSystemReady;
4432 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004433 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4434 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004435 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004437 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 }
4439
4440 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4441 if (VDBG) log("Got NetworkAgent Messenger");
4442 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004443 synchronized (mNetworkForNetId) {
4444 mNetworkForNetId.put(na.network.netId, na);
4445 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4447 NetworkInfo networkInfo = na.networkInfo;
4448 na.networkInfo = null;
4449 updateNetworkInfo(na, networkInfo);
4450 }
4451
4452 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4453 LinkProperties newLp = networkAgent.linkProperties;
4454 int netId = networkAgent.network.netId;
4455
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004456 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4457 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004458 if (networkAgent.clatd != null) {
4459 networkAgent.clatd.fixupLinkProperties(oldLp);
4460 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004461
Paul Jensen992f2522014-04-28 10:33:11 -04004462 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 updateMtu(newLp, oldLp);
4464 // TODO - figure out what to do for clat
4465// for (LinkProperties lp : newLp.getStackedLinks()) {
4466// updateMtu(lp, null);
4467// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004468 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004469
Erik Kline94887872016-04-05 13:30:49 +09004470 updateRoutes(newLp, oldLp, netId);
4471 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004472
Paul Jensen3b759822014-05-13 11:44:01 -04004473 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004474 if (isDefaultNetwork(networkAgent)) {
4475 handleApplyDefaultProxy(newLp.getHttpProxy());
4476 } else {
4477 updateProxy(newLp, oldLp, networkAgent);
4478 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004479 // TODO - move this check to cover the whole function
4480 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004481 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004482 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4483 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004484
4485 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004486 }
4487
Lorenzo Colitti95439462014-10-09 13:44:48 +09004488 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4489 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4490 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004491
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004492 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004493 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4494 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004495 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004496 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004497 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 }
Paul Jensen992f2522014-04-28 10:33:11 -04004499
4500 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4501 CompareResult<String> interfaceDiff = new CompareResult<String>();
4502 if (oldLp != null) {
4503 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4504 } else if (newLp != null) {
4505 interfaceDiff.added = newLp.getAllInterfaceNames();
4506 }
4507 for (String iface : interfaceDiff.added) {
4508 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004509 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004510 mNetd.addInterfaceToNetwork(iface, netId);
4511 } catch (Exception e) {
4512 loge("Exception adding interface: " + e);
4513 }
4514 }
4515 for (String iface : interfaceDiff.removed) {
4516 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004517 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004518 mNetd.removeInterfaceFromNetwork(iface, netId);
4519 } catch (Exception e) {
4520 loge("Exception removing interface: " + e);
4521 }
4522 }
4523 }
4524
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004525 /**
4526 * Have netd update routes from oldLp to newLp.
4527 * @return true if routes changed between oldLp and newLp
4528 */
4529 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4531 if (oldLp != null) {
4532 routeDiff = oldLp.compareAllRoutes(newLp);
4533 } else if (newLp != null) {
4534 routeDiff.added = newLp.getAllRoutes();
4535 }
4536
4537 // add routes before removing old in case it helps with continuous connectivity
4538
4539 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4540 for (RouteInfo route : routeDiff.added) {
4541 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004542 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 try {
4544 mNetd.addRoute(netId, route);
4545 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004546 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4547 loge("Exception in addRoute for non-gateway: " + e);
4548 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 }
4550 }
4551 for (RouteInfo route : routeDiff.added) {
4552 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004553 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 try {
4555 mNetd.addRoute(netId, route);
4556 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004557 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4558 loge("Exception in addRoute for gateway: " + e);
4559 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 }
4561 }
4562
4563 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004564 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 try {
4566 mNetd.removeRoute(netId, route);
4567 } catch (Exception e) {
4568 loge("Exception in removeRoute: " + e);
4569 }
4570 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004571 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 }
Erik Kline41368502015-06-17 13:19:54 +09004573
Erik Kline94887872016-04-05 13:30:49 +09004574 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4575 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4576 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004577 }
Erik Kline94887872016-04-05 13:30:49 +09004578
4579 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004580 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004581 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004582 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004583 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4584 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004585 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004586 }
Erik Kline94887872016-04-05 13:30:49 +09004587 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004588 }
4589
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004590 private String getNetworkPermission(NetworkCapabilities nc) {
4591 // TODO: make these permission strings AIDL constants instead.
4592 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4593 return NetworkManagementService.PERMISSION_SYSTEM;
4594 }
4595 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4596 return NetworkManagementService.PERMISSION_NETWORK;
4597 }
4598 return null;
4599 }
4600
Paul Jensen3d194ea2015-06-16 14:27:36 -04004601 /**
4602 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4603 * augmented with any stateful capabilities implied from {@code networkAgent}
4604 * (e.g., validated status and captive portal status).
4605 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004606 * @param oldScore score of the network before any of the changes that prompted us
4607 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004608 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004609 * @param networkCapabilities the new network capabilities.
4610 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004611 private void updateCapabilities(
4612 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004613 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4614 networkCapabilities)) {
4615 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4616 + nai.networkCapabilities + " -> " + networkCapabilities);
4617 }
4618
Paul Jensen3d194ea2015-06-16 14:27:36 -04004619 // Don't modify caller's NetworkCapabilities.
4620 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004621 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004622 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4623 } else {
4624 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4625 }
Paul Jensene0988542015-06-25 15:30:08 -04004626 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004627 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4628 } else {
4629 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4630 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004631 if (nai.isBackgroundNetwork()) {
4632 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4633 } else {
4634 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4635 }
4636
4637 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4638
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004639 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4640 final String newPermission = getNetworkPermission(networkCapabilities);
4641 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004642 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004643 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004644 } catch (RemoteException e) {
4645 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004646 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004647 }
4648
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004649 final NetworkCapabilities prevNc = nai.networkCapabilities;
4650 synchronized (nai) {
4651 nai.networkCapabilities = networkCapabilities;
4652 }
4653 if (nai.getCurrentScore() == oldScore &&
4654 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4655 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4656 // the change we're processing can't affect any requests, it can only affect the listens
4657 // on this network. We might have been called by rematchNetworkAndRequests when a
4658 // network changed foreground state.
4659 processListenRequests(nai, true);
4660 } else {
4661 // If the requestable capabilities have changed or the score changed, we can't have been
4662 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004663 rematchAllNetworksAndRequests(nai, oldScore);
4664 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004665 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004666 }
4667
Paul Jensenc8b9a742014-09-30 15:37:41 -04004668 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004669 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4670 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004671 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004672 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004673 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4674 }
4675 }
4676
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4678 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004679 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004680 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4681 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 }
4683 }
4684
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004685 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4686 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004687 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004688 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004689 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4690 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004691 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004692 sendIntent(nri.mPendingIntent, intent);
4693 }
4694 // else not handled
4695 }
4696
4697 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4698 mPendingIntentWakeLock.acquire();
4699 try {
4700 if (DBG) log("Sending " + pendingIntent);
4701 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4702 } catch (PendingIntent.CanceledException e) {
4703 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4704 mPendingIntentWakeLock.release();
4705 releasePendingNetworkRequest(pendingIntent);
4706 }
4707 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4708 }
4709
4710 @Override
4711 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4712 String resultData, Bundle resultExtras) {
4713 if (DBG) log("Finished sending " + pendingIntent);
4714 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004715 // Release with a delay so the receiving client has an opportunity to put in its
4716 // own request.
4717 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004718 }
4719
Robert Greenwalt9258c642014-03-26 16:47:06 -07004720 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004721 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004722 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004723 Bundle bundle = new Bundle();
4724 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4725 new NetworkRequest(nri.request));
4726 Message msg = Message.obtain();
4727 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4728 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4729 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4730 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004732 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004733 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004734 break;
4735 }
4736 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4737 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4738 new NetworkCapabilities(networkAgent.networkCapabilities));
4739 break;
4740 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004742 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4743 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004744 break;
4745 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004746 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004747 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004748 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004749 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004750 if (VDBG) {
4751 log("sending notification " + notifyTypeToName(notificationType) +
4752 " for " + nri.request);
4753 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004754 nri.messenger.send(msg);
4755 } catch (RemoteException e) {
4756 // may occur naturally in the race of binder death.
4757 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4758 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 }
4760
Paul Jensenc8b9a742014-09-30 15:37:41 -04004761 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004762 if (nai.numRequestNetworkRequests() != 0) {
4763 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4764 NetworkRequest nr = nai.requestAt(i);
4765 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004766 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004767 loge("Dead network still had at least " + nr);
4768 break;
4769 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004770 }
4771 nai.asyncChannel.disconnect();
4772 }
4773
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4775 if (oldNetwork == null) {
4776 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4777 return;
4778 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004779 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004780
4781 // If we get here it means that the last linger timeout for this network expired. So there
4782 // must be no other active linger timers, and we must stop lingering.
4783 oldNetwork.clearLingerState();
4784
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004785 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004786 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004787 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004788 } else {
4789 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004790 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4791 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004792 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793 }
4794
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004795 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004796 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004797 setupDataActivityTracking(newNetwork);
4798 try {
4799 mNetd.setDefaultNetId(newNetwork.network.netId);
4800 } catch (Exception e) {
4801 loge("Exception setting default network :" + e);
4802 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004803 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004804 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004805 updateTcpBufferSizes(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004806 }
4807
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004808 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004809 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4810 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4811 NetworkRequest nr = nri.request;
4812 if (!nr.isListen()) continue;
4813 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4814 nai.removeRequest(nri.request.requestId);
4815 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4816 }
4817 }
4818
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 if (capabilitiesChanged) {
4820 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4821 }
4822
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004823 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4824 NetworkRequest nr = nri.request;
4825 if (!nr.isListen()) continue;
4826 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4827 nai.addRequest(nr);
4828 notifyNetworkCallback(nai, nri);
4829 }
4830 }
4831 }
4832
Paul Jensen2161a8e2014-09-11 11:00:39 -04004833 // Handles a network appearing or improving its score.
4834 //
4835 // - Evaluates all current NetworkRequests that can be
4836 // satisfied by newNetwork, and reassigns to newNetwork
4837 // any such requests for which newNetwork is the best.
4838 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004839 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004840 // needed. A network is needed if it is the best network for
4841 // one or more NetworkRequests, or if it is a VPN.
4842 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004843 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004844 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004845 //
4846 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4847 // networks that have no chance (i.e. even if validated)
4848 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004849 //
4850 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4851 // it does not remove NetworkRequests that other Networks could better satisfy.
4852 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4853 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4854 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004855 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004856 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004857 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4858 // performed to tear down unvalidated networks that have no chance (i.e. even if
4859 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004860 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004861 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004862 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004863 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004864 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004865 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004866
4867 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4868 final int score = newNetwork.getCurrentScore();
4869
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004870 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004871
Paul Jensen2161a8e2014-09-11 11:00:39 -04004872 // Find and migrate to this Network any NetworkRequests for
4873 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004874 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004875 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004876 NetworkCapabilities nc = newNetwork.networkCapabilities;
4877 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004878 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004879 // Process requests in the first pass and listens in the second pass. This allows us to
4880 // change a network's capabilities depending on which requests it has. This is only
4881 // correct if the change in capabilities doesn't affect whether the network satisfies
4882 // requests or not, and doesn't affect the network's score.
4883 if (nri.request.isListen()) continue;
4884
Paul Jensencf4c2c62015-07-01 14:16:32 -04004885 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4886 final boolean satisfies = newNetwork.satisfies(nri.request);
4887 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004888 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004889 log("Network " + newNetwork.name() + " was already satisfying" +
4890 " request " + nri.request.requestId + ". No change.");
4891 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004892 keep = true;
4893 continue;
4894 }
4895
4896 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004898 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004899 // next check if it's better than any current network we're using for
4900 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004901 if (VDBG) {
4902 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004903 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004904 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004906 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004907 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004908 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004909 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004910 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004911 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004912 affectedNetworks.add(currentNetwork);
4913 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004914 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004915 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004916 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004917 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004918 if (!newNetwork.addRequest(nri.request)) {
4919 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4920 }
4921 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004922 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004923 // Tell NetworkFactories about the new score, so they can stop
4924 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 // TODO - this could get expensive if we have alot of requests for this
4926 // network. Think about if there is a way to reduce this. Push
4927 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004928 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004929 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004930 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004931 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004932 if (currentNetwork != null) {
4933 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 }
4936 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004937 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004938 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4939 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004940 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004941 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4942 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4943 // This means this code doesn't have to handle the case where "currentNetwork" no
4944 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4945 if (DBG) {
4946 log("Network " + newNetwork.name() + " stopped satisfying" +
4947 " request " + nri.request.requestId);
4948 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004949 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004950 if (currentNetwork == newNetwork) {
4951 mNetworkForRequestId.remove(nri.request.requestId);
4952 sendUpdatedScoreToFactories(nri.request, 0);
4953 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004954 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4955 newNetwork.name() +
4956 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004957 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004958 // TODO: Technically, sending CALLBACK_LOST here is
4959 // incorrect if there is a replacement network currently
4960 // connected that can satisfy nri, which is a request
4961 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004962 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4963 // so this code is only incorrect for a network that loses
4964 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004965 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004966 }
4967 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004968 if (isNewDefault) {
4969 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004970 makeDefault(newNetwork);
4971 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4972 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 synchronized (ConnectivityService.this) {
4974 // have a new default network, release the transition wakelock in
4975 // a second if it's held. The second pause is to allow apps
4976 // to reconnect over the new network
4977 if (mNetTransitionWakeLock.isHeld()) {
4978 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4979 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4980 mNetTransitionWakeLockSerialNumber, 0),
4981 1000);
4982 }
4983 }
4984 }
4985
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004986 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4987 Slog.wtf(TAG, String.format(
4988 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4989 nc, newNetwork.networkCapabilities));
4990 }
4991 if (newNetwork.getCurrentScore() != score) {
4992 Slog.wtf(TAG, String.format(
4993 "BUG: %s changed score during rematch: %d -> %d",
4994 score, newNetwork.getCurrentScore()));
4995 }
4996
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004997 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004998 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4999 // If the network went from background to foreground or vice versa, we need to update
5000 // its foreground state. It is safe to do this after rematching the requests because
5001 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5002 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005003 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005004 } else {
5005 processListenRequests(newNetwork, false);
5006 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005007
Paul Jensencf4c2c62015-07-01 14:16:32 -04005008 // do this after the default net is switched, but
5009 // before LegacyTypeTracker sends legacy broadcasts
5010 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
5011
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005012 // Linger any networks that are no longer needed. This should be done after sending the
5013 // available callback for newNetwork.
5014 for (NetworkAgentInfo nai : affectedNetworks) {
5015 updateLingerState(nai, now);
5016 }
5017 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5018 // does not need to be done in any particular order.
5019 updateLingerState(newNetwork, now);
5020
Paul Jensencf4c2c62015-07-01 14:16:32 -04005021 if (isNewDefault) {
5022 // Maintain the illusion: since the legacy API only
5023 // understands one network at a time, we must pretend
5024 // that the current default network disconnected before
5025 // the new one connected.
5026 if (oldDefaultNetwork != null) {
5027 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5028 oldDefaultNetwork, true);
5029 }
5030 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5031 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5032 notifyLockdownVpn(newNetwork);
5033 }
5034
Robert Greenwalt7b816022014-04-18 15:25:25 -07005035 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005036 // Notify battery stats service about this network, both the normal
5037 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005038 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005039 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005040 final IBatteryStats bs = BatteryStatsService.getService();
5041 final int type = newNetwork.networkInfo.getType();
5042
5043 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5044 bs.noteNetworkInterfaceType(baseIface, type);
5045 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5046 final String stackedIface = stacked.getInterfaceName();
5047 bs.noteNetworkInterfaceType(stackedIface, type);
5048 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5049 }
5050 } catch (RemoteException ignored) {
5051 }
5052
Robert Greenwalt152ed372014-12-17 17:19:53 -08005053 // This has to happen after the notifyNetworkCallbacks as that tickles each
5054 // ConnectivityManager instance so that legacy requests correctly bind dns
5055 // requests to this network. The legacy users are listening for this bcast
5056 // and will generally do a dns request so they can ensureRouteToHost and if
5057 // they do that before the callbacks happen they'll use the default network.
5058 //
5059 // TODO: Is there still a race here? We send the broadcast
5060 // after sending the callback, but if the app can receive the
5061 // broadcast before the callback, it might still break.
5062 //
5063 // This *does* introduce a race where if the user uses the new api
5064 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5065 // they may get old info. Reverse this after the old startUsing api is removed.
5066 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005067 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5068 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005069 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005070 // legacy type tracker filters out repeat adds
5071 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5072 }
5073 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005074
5075 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5076 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5077 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5078 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5079 if (newNetwork.isVPN()) {
5080 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5081 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005082 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005083 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5084 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005085 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005086 if (nai.getLingerExpiry() > 0) {
5087 // This network has active linger timers and no requests, but is not
5088 // lingering. Linger it.
5089 //
5090 // One way (the only way?) this can happen if this network is unvalidated
5091 // and became unneeded due to another network improving its score to the
5092 // point where this network will no longer be able to satisfy any requests
5093 // even if it validates.
5094 updateLingerState(nai, now);
5095 } else {
5096 if (DBG) log("Reaping " + nai.name());
5097 teardownUnneededNetwork(nai);
5098 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005099 }
5100 }
5101 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005102 }
5103
Paul Jensen1c7ba022015-06-16 14:27:36 -04005104 /**
5105 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5106 * being disconnected.
5107 * @param changed If only one Network's score or capabilities have been modified since the last
5108 * time this function was called, pass this Network in this argument, otherwise pass
5109 * null.
5110 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5111 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5112 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5113 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5114 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005115 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005116 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005117 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5118 // to avoid the slowness. It is not simply enough to process just "changed", for
5119 // example in the case where "changed"'s score decreases and another network should begin
5120 // satifying a NetworkRequest that "changed" currently satisfies.
5121
5122 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5123 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5124 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005125 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005126 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005127 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005128 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005129 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5130 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5131 // Rematch higher scoring networks first to prevent requests first matching a lower
5132 // scoring network and then a higher scoring network, which could produce multiple
5133 // callbacks and inadvertently unlinger networks.
5134 Arrays.sort(nais);
5135 for (NetworkAgentInfo nai : nais) {
5136 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005137 // Only reap the last time through the loop. Reaping before all rematching
5138 // is complete could incorrectly teardown a network that hasn't yet been
5139 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005140 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005141 : ReapUnvalidatedNetworks.REAP,
5142 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005143 }
5144 }
5145 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005147 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005148 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005149 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005150 // For now only update icons for default connection.
5151 // TODO: Update WiFi and cellular icons separately. b/17237507
5152 if (!isDefaultNetwork(nai)) return;
5153
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005154 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005155 // Don't repeat publish.
5156 if (newInetCondition == mDefaultInetConditionPublished) return;
5157
5158 mDefaultInetConditionPublished = newInetCondition;
5159 sendInetConditionBroadcast(nai.networkInfo);
5160 }
5161
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005162 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5163 if (mLockdownTracker != null) {
5164 if (nai != null && nai.isVPN()) {
5165 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5166 } else {
5167 mLockdownTracker.onNetworkInfoChanged();
5168 }
5169 }
5170 }
5171
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5173 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005174 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005175 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005176 synchronized (networkAgent) {
5177 oldInfo = networkAgent.networkInfo;
5178 networkAgent.networkInfo = newInfo;
5179 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005180 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005181
5182 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005183 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5184 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5185 notifyIfacesChangedForNetworkStats();
5186 } else if (VDBG) log("ignoring duplicate network state non-change");
5187 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005188 return;
5189 }
5190 if (DBG) {
5191 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5192 (oldInfo == null ? "null" : oldInfo.getState()) +
5193 " to " + state);
5194 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005195
Robin Lee585e2482016-05-01 23:00:00 +01005196 if (!networkAgent.created
5197 && (state == NetworkInfo.State.CONNECTED
5198 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005199
5200 // A network that has just connected has zero requests and is thus a foreground network.
5201 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5202
Robert Greenwalt7b816022014-04-18 15:25:25 -07005203 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005204 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005205 if (networkAgent.isVPN()) {
5206 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005207 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5208 (networkAgent.networkMisc == null ||
5209 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005210 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005211 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005212 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005213 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005214 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005215 loge("Error creating network " + networkAgent.network.netId + ": "
5216 + e.getMessage());
5217 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005218 }
Paul Jenseneec75412014-08-04 12:21:19 -04005219 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005220 }
5221
5222 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5223 networkAgent.everConnected = true;
5224
Robert Greenwalt7b816022014-04-18 15:25:25 -07005225 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005226 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005227
Paul Jensenca8f16a2014-05-09 12:47:55 -04005228 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005229 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005230
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005231 if (networkAgent.isVPN()) {
5232 // Temporarily disable the default proxy (not global).
5233 synchronized (mProxyLock) {
5234 if (!mDefaultProxyDisabled) {
5235 mDefaultProxyDisabled = true;
5236 if (mGlobalProxy == null && mDefaultProxy != null) {
5237 sendProxyBroadcast(null);
5238 }
5239 }
5240 }
5241 // TODO: support proxy per network.
5242 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005243
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005244 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5245 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5246 // capabilities, so it only needs to be done once on initial connect, not every time the
5247 // network's capabilities change. Note that we do this before rematching the network,
5248 // so we could decide to tear it down immediately afterwards. That's fine though - on
5249 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5250 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005251 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005252
Paul Jensen2161a8e2014-09-11 11:00:39 -04005253 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005254 final long now = SystemClock.elapsedRealtime();
5255 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005256
5257 // This has to happen after matching the requests, because callbacks are just requests.
5258 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005259 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005260 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005261 if (networkAgent.isVPN()) {
5262 synchronized (mProxyLock) {
5263 if (mDefaultProxyDisabled) {
5264 mDefaultProxyDisabled = false;
5265 if (mGlobalProxy == null && mDefaultProxy != null) {
5266 sendProxyBroadcast(mDefaultProxy);
5267 }
5268 }
5269 }
5270 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005271 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5272 state == NetworkInfo.State.SUSPENDED) {
5273 // going into or coming out of SUSPEND: rescore and notify
5274 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005275 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005276 }
5277 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5278 ConnectivityManager.CALLBACK_SUSPENDED :
5279 ConnectivityManager.CALLBACK_RESUMED));
5280 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 }
5282 }
5283
Robert Greenwaltac96c522014-06-03 16:43:57 -07005284 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005285 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005286 if (score < 0) {
5287 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5288 "). Bumping score to min of 0");
5289 score = 0;
5290 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005291
Paul Jensen2161a8e2014-09-11 11:00:39 -04005292 final int oldScore = nai.getCurrentScore();
5293 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005294
Paul Jensen85cf78e2015-06-25 13:25:07 -04005295 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005296
Paul Jensenc8b9a742014-09-30 15:37:41 -04005297 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005298 }
5299
Robert Greenwalt9258c642014-03-26 16:47:06 -07005300 // notify only this one new request of the current state
5301 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5302 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005303 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005304 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005305 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005306 } else {
5307 sendPendingIntentForRequest(nri, nai, notifyType);
5308 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005309 }
5310
Robert Greenwalt8d482522015-06-24 13:23:42 -07005311 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005312 // The NetworkInfo we actually send out has no bearing on the real
5313 // state of affairs. For example, if the default connection is mobile,
5314 // and a request for HIPRI has just gone away, we need to pretend that
5315 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5316 // the state to DISCONNECTED, even though the network is of type MOBILE
5317 // and is still connected.
5318 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5319 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005320 if (state != DetailedState.DISCONNECTED) {
5321 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005322 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005323 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005324 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005325 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5326 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5327 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5328 if (info.isFailover()) {
5329 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5330 nai.networkInfo.setFailover(false);
5331 }
5332 if (info.getReason() != null) {
5333 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5334 }
5335 if (info.getExtraInfo() != null) {
5336 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5337 }
5338 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005339 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005340 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005341 if (newDefaultAgent != null) {
5342 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5343 newDefaultAgent.networkInfo);
5344 } else {
5345 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5346 }
5347 }
5348 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5349 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005350 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005351 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005352 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005353 }
5354 }
5355 }
5356
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005357 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005358 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005359 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5360 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005361 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5362 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005363 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5364 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005365 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005366 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005367 } else {
5368 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5369 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005370 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005371 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005372
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005373 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5374 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5375 }
5376
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005377 private String notifyTypeToName(int notifyType) {
5378 switch (notifyType) {
5379 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5380 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5381 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5382 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5383 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5384 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5385 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5386 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5387 }
5388 return "UNKNOWN";
5389 }
5390
Jeff Sharkey69736342014-12-08 14:50:12 -08005391 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005392 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5393 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005394 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005395 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005396 try {
5397 mStatsService.forceUpdateIfaces();
5398 } catch (Exception ignored) {
5399 }
5400 }
5401
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005402 @Override
5403 public boolean addVpnAddress(String address, int prefixLength) {
5404 throwIfLockdownEnabled();
5405 int user = UserHandle.getUserId(Binder.getCallingUid());
5406 synchronized (mVpns) {
5407 return mVpns.get(user).addAddress(address, prefixLength);
5408 }
5409 }
5410
5411 @Override
5412 public boolean removeVpnAddress(String address, int prefixLength) {
5413 throwIfLockdownEnabled();
5414 int user = UserHandle.getUserId(Binder.getCallingUid());
5415 synchronized (mVpns) {
5416 return mVpns.get(user).removeAddress(address, prefixLength);
5417 }
5418 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005419
5420 @Override
5421 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5422 throwIfLockdownEnabled();
5423 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005424 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005425 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005426 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005427 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005428 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005429 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005430 }
5431 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005432 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005433
5434 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005435 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005436 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005437 }
5438
5439 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005440 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5441 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5442 enforceKeepalivePermission();
5443 mKeepaliveTracker.startNattKeepalive(
5444 getNetworkAgentInfoForNetwork(network),
5445 intervalSeconds, messenger, binder,
5446 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5447 }
5448
5449 @Override
5450 public void stopKeepalive(Network network, int slot) {
5451 mHandler.sendMessage(mHandler.obtainMessage(
5452 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5453 }
5454
5455 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005456 public void factoryReset() {
5457 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005458
5459 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5460 return;
5461 }
5462
Robin Lee3b3dd942015-05-12 18:14:58 +01005463 final int userId = UserHandle.getCallingUserId();
5464
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465 // Turn airplane mode off
5466 setAirplaneMode(false);
5467
Stuart Scotte3e314d2015-04-20 14:07:45 -07005468 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5469 // Untether
5470 for (String tether : getTetheredIfaces()) {
5471 untether(tether);
5472 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005473 }
5474
Stuart Scotte3e314d2015-04-20 14:07:45 -07005475 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005476 // Remove always-on package
5477 synchronized (mVpns) {
5478 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5479 if (alwaysOnPackage != null) {
5480 setAlwaysOnVpnPackage(userId, null, false);
5481 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5482 }
5483 }
5484
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005485 // Turn Always-on VPN off
5486 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5487 final long ident = Binder.clearCallingIdentity();
5488 try {
5489 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5490 mLockdownEnabled = false;
5491 setLockdownTracker(null);
5492 } finally {
5493 Binder.restoreCallingIdentity(ident);
5494 }
5495 }
5496
Stuart Scotte3e314d2015-04-20 14:07:45 -07005497 // Turn VPN off
5498 VpnConfig vpnConfig = getVpnConfig(userId);
5499 if (vpnConfig != null) {
5500 if (vpnConfig.legacy) {
5501 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5502 } else {
5503 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5504 // in the future without user intervention.
5505 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005506
Victor Changb04a5ea2016-05-30 20:36:30 +01005507 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005508 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005509 }
5510 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005511
5512 Settings.Global.putString(mContext.getContentResolver(),
5513 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005514 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005515
5516 @VisibleForTesting
5517 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5518 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5519 return new NetworkMonitor(context, handler, nai, defaultRequest);
5520 }
Erik Kline48f12f22016-04-14 17:30:59 +09005521
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005522 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005523 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5524 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005525 }
5526
5527 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005528 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5529 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5530 }
5531
Hugo Benichicfddd682016-05-31 16:28:06 +09005532 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005533 int newNetid = NETID_UNSET;
5534 int prevNetid = NETID_UNSET;
5535 int[] transports = new int[0];
5536 boolean hadIPv4 = false;
5537 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005538
Hugo Benichi5f16f762016-04-20 12:09:33 +09005539 if (newNai != null) {
5540 newNetid = newNai.network.netId;
5541 transports = newNai.networkCapabilities.getTransportTypes();
5542 }
5543 if (prevNai != null) {
5544 prevNetid = prevNai.network.netId;
5545 final LinkProperties lp = prevNai.linkProperties;
5546 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5547 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5548 }
5549
Hugo Benichicfddd682016-05-31 16:28:06 +09005550 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5551 }
5552
5553 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5554 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556}