blob: d325ea7a978825c2a851c72f97e7a5963cba2a05 [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
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900398 private static String eventName(int what) {
399 return sMagicDecoderRing.get(what, Integer.toString(what));
400 }
401
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900402 /** Handler thread used for both of the handlers below. */
403 @VisibleForTesting
404 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700407 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700408 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700409
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800411 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400412
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700413 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700414 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800415 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416
Robert Greenwalt434203a2010-10-11 16:00:27 -0700417 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400418 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700419 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700420 private boolean mDefaultProxyDisabled = false;
421
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400423 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700424
Jason Monk602b2322013-07-03 17:04:33 -0400425 private PacManager mPacManager = null;
426
Erik Klineda4bfa82015-04-30 12:58:40 +0900427 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700428
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400429 private UserManager mUserManager;
430
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700431 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700432 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700433
Robert Greenwalt50393202011-06-21 17:26:14 -0700434 // the set of network types that can only be enabled by system/sig apps
435 List mProtectedNetworks;
436
John Spurlockbf991a82013-06-24 14:20:23 -0400437 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700438
Wink Savilleab9321d2013-06-29 21:10:57 -0700439 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400440
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900441 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900442 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900443 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900444
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700445 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
446 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700447 private final static int MAX_NET_ID = 65535;
448 private int mNextNetId = MIN_NET_ID;
449
Robert Greenwalt34524f02014-05-18 16:22:10 -0700450 // sequence number of NetworkRequests
451 private int mNextNetworkRequestId = 1;
452
Erik Kline7523eb32015-07-09 18:24:03 +0900453 // NetworkRequest activity String log entries.
454 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
455 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
456
Hugo Benichic2ae2872016-07-11 11:05:12 +0900457 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900458 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900459 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
460
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900461 private static final int MAX_WAKELOCK_LOGS = 20;
462 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
463
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700464 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
465 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400466 private static class ValidationLog {
467 final Network mNetwork;
468 final String mNetworkExtraInfo;
469 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700470
Paul Jensen0808eb82016-06-03 13:51:21 -0400471 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
472 mNetwork = network;
473 mNetworkExtraInfo = networkExtraInfo;
474 mLog = log;
475 }
476 }
477 private final ArrayDeque<ValidationLog> mValidationLogs =
478 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
479
480 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700481 synchronized(mValidationLogs) {
482 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
483 mValidationLogs.removeLast();
484 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400485 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700486 }
487 }
488
Hugo Benichif9fdf872016-07-28 17:53:06 +0900489 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900490
Erik Kline065ab6e2016-10-02 18:02:14 +0900491 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900492 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900493
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700494 /**
495 * Implements support for the legacy "one network per network type" model.
496 *
497 * We used to have a static array of NetworkStateTrackers, one for each
498 * network type, but that doesn't work any more now that we can have,
499 * for example, more that one wifi network. This class stores all the
500 * NetworkAgentInfo objects that support a given type, but the legacy
501 * API will only see the first one.
502 *
503 * It serves two main purposes:
504 *
505 * 1. Provide information about "the network for a given type" (since this
506 * API only supports one).
507 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
508 * the first network for a given type changes, or if the default network
509 * changes.
510 */
511 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900512
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900513 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700516 /**
517 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
518 * Each list holds references to all NetworkAgentInfos that are used to
519 * satisfy requests for that network type.
520 *
521 * This array is built out at startup such that an unsupported network
522 * doesn't get an ArrayList instance, making this a tristate:
523 * unsupported, supported but not active and active.
524 *
525 * The actual lists are populated when we scan the network types that
526 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900527 *
528 * Threading model:
529 * - addSupportedType() is only called in the constructor
530 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
531 * They are therefore not thread-safe with respect to each other.
532 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
533 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
534 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900536 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537
538 public LegacyTypeTracker() {
539 mTypeLists = (ArrayList<NetworkAgentInfo>[])
540 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
541 }
542
543 public void addSupportedType(int type) {
544 if (mTypeLists[type] != null) {
545 throw new IllegalStateException(
546 "legacy list for type " + type + "already initialized");
547 }
548 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
549 }
550
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551 public boolean isTypeSupported(int type) {
552 return isNetworkTypeValid(type) && mTypeLists[type] != null;
553 }
554
555 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900556 synchronized (mTypeLists) {
557 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
558 return mTypeLists[type].get(0);
559 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900561 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900565 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900566 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900569 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 }
571 }
572
573 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 public void add(int type, NetworkAgentInfo nai) {
575 if (!isTypeSupported(type)) {
576 return; // Invalid network type.
577 }
578 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
579
580 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
581 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700582 return;
583 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 synchronized (mTypeLists) {
585 list.add(nai);
586 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900587
588 // 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 +0900589 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900590 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
592 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
595
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900597 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
599 if (list == null || list.isEmpty()) {
600 return;
601 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900602 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 synchronized (mTypeLists) {
605 if (!list.remove(nai)) {
606 return;
607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 }
609
Robert Greenwalt8d482522015-06-24 13:23:42 -0700610 final DetailedState state = DetailedState.DISCONNECTED;
611
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700613 maybeLogBroadcast(nai, state, type, wasDefault);
614 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900615 }
616
617 if (!list.isEmpty() && wasFirstNetwork) {
618 if (DBG) log("Other network available for type " + type +
619 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900620 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700621 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
622 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900623 }
624 }
625
626 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900627 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
628 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 }
632 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700633
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 // send out another legacy broadcast - currently only used for suspend/unsuspend
635 // toggle
636 public void update(NetworkAgentInfo nai) {
637 final boolean isDefault = isDefaultNetwork(nai);
638 final DetailedState state = nai.networkInfo.getDetailedState();
639 for (int type = 0; type < mTypeLists.length; type++) {
640 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700641 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 final boolean isFirst = contains && (nai == list.get(0));
643 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 maybeLogBroadcast(nai, state, type, isDefault);
645 sendLegacyNetworkBroadcast(nai, state, type);
646 }
647 }
648 }
649
Lorenzo Colittia793a672014-07-31 23:20:17 +0900650 private String naiToString(NetworkAgentInfo nai) {
651 String name = (nai != null) ? nai.name() : "null";
652 String state = (nai.networkInfo != null) ?
653 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
654 "???/???";
655 return name + " " + state;
656 }
657
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700658 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900659 pw.println("mLegacyTypeTracker:");
660 pw.increaseIndent();
661 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900663 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700664 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 pw.println();
666 pw.println("Current state:");
667 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900668 synchronized (mTypeLists) {
669 for (int type = 0; type < mTypeLists.length; type++) {
670 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
671 for (NetworkAgentInfo nai : mTypeLists[type]) {
672 pw.println(type + " " + naiToString(nai));
673 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900674 }
675 }
676 pw.decreaseIndent();
677 pw.decreaseIndent();
678 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700679 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 }
681 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
682
Jeff Sharkey899223b2012-08-04 15:24:58 -0700683 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700684 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900685 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
686 }
687
688 @VisibleForTesting
689 protected ConnectivityService(Context context, INetworkManagementService netManager,
690 INetworkStatsService statsService, INetworkPolicyManager policyManager,
691 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800692 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800693
Hugo Benichif9fdf872016-07-28 17:53:06 +0900694 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900695 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900696 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900697 mNetworkRequests.put(mDefaultRequest, defaultNRI);
698 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900699
700 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900701 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700702
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900703 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900704 mHandlerThread.start();
705 mHandler = new InternalHandler(mHandlerThread.getLooper());
706 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700707
Jeremy Joslin79294842014-12-03 17:15:28 -0800708 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
709 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
710
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900711 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
712
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700713 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700714 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800715 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700716 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700717 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700718 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700719
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700720 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600721 mPolicyManager.setConnectivityListener(mPolicyListener);
722 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700723 } catch (RemoteException e) {
724 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700725 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 }
727
728 final PowerManager powerManager = (PowerManager) context.getSystemService(
729 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700730 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
731 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
732 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800733 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700734
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700735 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700736
Wink Saville51f456f2013-04-23 14:26:51 -0700737 // TODO: What is the "correct" way to do determine if this is a wifi only device?
738 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
739 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700740 String[] naStrings = context.getResources().getStringArray(
741 com.android.internal.R.array.networkAttributes);
742 for (String naString : naStrings) {
743 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700744 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700745 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700746 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800747 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700748 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700749 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700750 }
Wink Saville51f456f2013-04-23 14:26:51 -0700751 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
752 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
753 n.type);
754 continue;
755 }
Wink Saville975c8482011-04-07 14:23:45 -0700756 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800757 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700758 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759 continue;
760 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700761 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700762
Wink Saville975c8482011-04-07 14:23:45 -0700763 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 mNetworksDefined++;
765 } catch(Exception e) {
766 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700767 }
768 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700769
770 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
771 if (mNetConfigs[TYPE_VPN] == null) {
772 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
773 // don't need to add TYPE_VPN to mNetConfigs.
774 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
775 mNetworksDefined++; // used only in the log() statement below.
776 }
777
Wink Saville5e56bc52013-07-29 15:00:57 -0700778 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700779
Robert Greenwalt50393202011-06-21 17:26:14 -0700780 mProtectedNetworks = new ArrayList<Integer>();
781 int[] protectedNetworks = context.getResources().getIntArray(
782 com.android.internal.R.array.config_protectedNetworks);
783 for (int p : protectedNetworks) {
784 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
785 mProtectedNetworks.add(p);
786 } else {
787 if (DBG) loge("Ignoring protectedNetwork " + p);
788 }
789 }
790
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700791 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
792 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700793
Christopher Wiley497c1472016-10-11 13:26:03 -0700794 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
795 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800796
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700797 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
798
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700799 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700800 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100801 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700802 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700803 intentFilter.addAction(Intent.ACTION_USER_ADDED);
804 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000805 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700806 mContext.registerReceiverAsUser(
807 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000808 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
809 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900810
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700811 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700812 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700813 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700814 } catch (RemoteException e) {
815 loge("Error registering observer :" + e);
816 }
817
Erik Klineda4bfa82015-04-30 12:58:40 +0900818 mSettingsObserver = new SettingsObserver(mContext, mHandler);
819 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800820
John Spurlockbf991a82013-06-24 14:20:23 -0400821 mDataConnectionStats = new DataConnectionStats(mContext);
822 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400823
Jason Monkdecd2952013-10-10 14:02:51 -0400824 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700825
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400826 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900827
828 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900829 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
830 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900831
832 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
833 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
834 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
835 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
836 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
837 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
838 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900839
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900840 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900841 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900842 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700844
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900845 private NetworkRequest createInternetRequestForTransport(
846 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900847 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900848 netCap.addCapability(NET_CAPABILITY_INTERNET);
849 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900850 if (transportType > -1) {
851 netCap.addTransportType(transportType);
852 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900853 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900854 }
855
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900856 // Used only for testing.
857 // TODO: Delete this and either:
858 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
859 // changing ContentResolver to make registerContentObserver non-final).
860 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
861 // by subclassing SettingsObserver.
862 @VisibleForTesting
863 void updateMobileDataAlwaysOn() {
864 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
865 }
866
Erik Klineda4bfa82015-04-30 12:58:40 +0900867 private void handleMobileDataAlwaysOn() {
868 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900869 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900870 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
871 if (enable == isEnabled) {
872 return; // Nothing to do.
873 }
874
875 if (enable) {
876 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900877 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900878 } else {
879 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
880 }
881 }
882
883 private void registerSettingsCallbacks() {
884 // Watch for global HTTP proxy changes.
885 mSettingsObserver.observe(
886 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
887 EVENT_APPLY_GLOBAL_HTTP_PROXY);
888
889 // Watch for whether or not to keep mobile data always on.
890 mSettingsObserver.observe(
891 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
892 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
893 }
894
Robert Greenwalt34524f02014-05-18 16:22:10 -0700895 private synchronized int nextNetworkRequestId() {
896 return mNextNetworkRequestId++;
897 }
898
Paul Jensen67b0b072015-06-10 11:22:17 -0400899 @VisibleForTesting
900 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400901 synchronized (mNetworkForNetId) {
902 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
903 int netId = mNextNetId;
904 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
905 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500906 if (!mNetIdInUse.get(netId)) {
907 mNetIdInUse.put(netId, true);
908 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400909 }
910 }
911 }
912 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700913 }
914
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600915 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600917 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
918 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800919 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600920 state = nai.getNetworkState();
921 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800922 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600923 final NetworkInfo info = new NetworkInfo(networkType, 0,
924 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800925 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
926 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600927 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
928 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600930 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600931 return state;
932 } else {
933 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400935 }
936
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800937 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
938 if (network == null) {
939 return null;
940 }
941 synchronized (mNetworkForNetId) {
942 return mNetworkForNetId.get(network.netId);
943 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900946 private Network[] getVpnUnderlyingNetworks(int uid) {
947 if (!mLockdownEnabled) {
948 int user = UserHandle.getUserId(uid);
949 synchronized (mVpns) {
950 Vpn vpn = mVpns.get(user);
951 if (vpn != null && vpn.appliesToUid(uid)) {
952 return vpn.getUnderlyingNetworks();
953 }
954 }
955 }
956 return null;
957 }
958
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400960 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800961
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900962 final Network[] networks = getVpnUnderlyingNetworks(uid);
963 if (networks != null) {
964 // getUnderlyingNetworks() returns:
965 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
966 // empty array => the VPN explicitly said "no default network".
967 // non-empty array => the VPN specified one or more default networks; we use the
968 // first one.
969 if (networks.length > 0) {
970 nai = getNetworkAgentInfoForNetwork(networks[0]);
971 } else {
972 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800973 }
974 }
975
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600977 return nai.getNetworkState();
978 } else {
979 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800980 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400981 }
982
983 /**
984 * Check if UID should be blocked from using the network with the given LinkProperties.
985 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600986 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
987 boolean ignoreBlocked) {
988 // Networks aren't blocked when ignoring blocked status
989 if (ignoreBlocked) return false;
990 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700991 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600992
993 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700994 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700995
Robin Lee17e61832016-05-09 13:46:28 +0100996 synchronized (mVpns) {
997 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
998 if (vpn != null && vpn.isBlockingUid(uid)) {
999 return true;
1000 }
1001 }
1002
Robert Greenwalt12e67352014-05-13 21:41:06 -07001003 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001004 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001005 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001006 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001007 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001008
Felipe Lemed31a97f2016-05-06 14:53:50 -07001009 boolean allowed = true;
1010 // Check Data Saver Mode first...
1011 if (networkMetered) {
1012 if ((uidRules & RULE_REJECT_METERED) != 0) {
1013 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1014 // Explicitly blacklisted.
1015 allowed = false;
1016 } else {
1017 allowed = !mRestrictBackground
1018 || (uidRules & RULE_ALLOW_METERED) != 0
1019 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1020 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1021 + " mRestrictBackground=" + mRestrictBackground
1022 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1023 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1024 + ": " + allowed);
1025 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001026 }
Felipe Leme781ba142016-05-09 16:24:48 -07001027 // ...then power restrictions.
1028 if (allowed) {
1029 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001030 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001031 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001032 }
1033 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 }
1035
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001036 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001037 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1038 return;
1039 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001040 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001041 synchronized (mBlockedAppUids) {
1042 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001043 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001044 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001045 blocked = false;
1046 } else {
1047 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001048 }
1049 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001050 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1051 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1052 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001053 }
1054
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001055 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1057 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1058 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1059 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001061 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001062 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1063
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001064 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001066 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 if (mLockdownTracker != null) {
1068 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001069 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001070
1071 // TODO: apply metered state closer to NetworkAgentInfo
1072 final long token = Binder.clearCallingIdentity();
1073 try {
1074 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1075 } catch (RemoteException e) {
1076 } finally {
1077 Binder.restoreCallingIdentity(token);
1078 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 }
1080
1081 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 * Return NetworkInfo for the active (i.e., connected) network interface.
1083 * It is assumed that at most one network is active at a time. If more
1084 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001085 * @return the info for the active network, or {@code null} if none is
1086 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001090 enforceAccessPermission();
1091 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001092 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001093 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001094 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1095 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
1097
Paul Jensen31a94f42015-02-13 14:18:39 -05001098 @Override
1099 public Network getActiveNetwork() {
1100 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001102 }
1103
1104 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001106 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001107 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001108 }
1109
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001111 final int user = UserHandle.getUserId(uid);
1112 int vpnNetId = NETID_UNSET;
1113 synchronized (mVpns) {
1114 final Vpn vpn = mVpns.get(user);
1115 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1116 }
1117 NetworkAgentInfo nai;
1118 if (vpnNetId != NETID_UNSET) {
1119 synchronized (mNetworkForNetId) {
1120 nai = mNetworkForNetId.get(vpnNetId);
1121 }
1122 if (nai != null) return nai.network;
1123 }
1124 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 if (nai != null
1126 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1127 nai = null;
1128 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001129 return nai != null ? nai.network : null;
1130 }
1131
Lorenzo Colitti18660282016-07-04 12:55:44 +09001132 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001133 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1134 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001135 final int uid = Binder.getCallingUid();
1136 NetworkState state = getUnfilteredActiveNetworkState(uid);
1137 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001138 }
1139
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001146 }
1147
1148 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 public NetworkInfo getNetworkInfo(int networkType) {
1150 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001152 if (getVpnUnderlyingNetworks(uid) != null) {
1153 // A VPN is active, so we may need to return one of its underlying networks. This
1154 // information is not available in LegacyTypeTracker, so we have to get it from
1155 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001157 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001160 }
1161 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
1165
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001169 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 return state.networkInfo;
1174 } else {
1175 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001176 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001177 }
1178
1179 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 public NetworkInfo[] getAllNetworkInfo() {
1181 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001182 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001183 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1184 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 NetworkInfo info = getNetworkInfo(networkType);
1186 if (info != null) {
1187 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001190 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
1192
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001193 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001194 public Network getNetworkForType(int networkType) {
1195 enforceAccessPermission();
1196 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001197 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1198 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001200 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001202 }
1203
1204 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001205 public Network[] getAllNetworks() {
1206 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001207 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001208 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001209 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001210 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001211 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001212 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001213 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 }
1215
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001216 @Override
1217 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1218 // The basic principle is: if an app's traffic could possibly go over a
1219 // network, without the app doing anything multinetwork-specific,
1220 // (hence, by "default"), then include that network's capabilities in
1221 // the array.
1222 //
1223 // In the normal case, app traffic only goes over the system's default
1224 // network connection, so that's the only network returned.
1225 //
1226 // With a VPN in force, some app traffic may go into the VPN, and thus
1227 // over whatever underlying networks the VPN specifies, while other app
1228 // traffic may go over the system default network (e.g.: a split-tunnel
1229 // VPN, or an app disallowed by the VPN), so the set of networks
1230 // returned includes the VPN's underlying networks and the system
1231 // default.
1232 enforceAccessPermission();
1233
1234 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1235
1236 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001237 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001238 if (nc != null) {
1239 result.put(nai.network, nc);
1240 }
1241
1242 if (!mLockdownEnabled) {
1243 synchronized (mVpns) {
1244 Vpn vpn = mVpns.get(userId);
1245 if (vpn != null) {
1246 Network[] networks = vpn.getUnderlyingNetworks();
1247 if (networks != null) {
1248 for (Network network : networks) {
1249 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001250 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001251 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001252 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001253 }
1254 }
1255 }
1256 }
1257 }
1258 }
1259
1260 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1261 out = result.values().toArray(out);
1262 return out;
1263 }
1264
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001265 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001266 public boolean isNetworkSupported(int networkType) {
1267 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001268 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001269 }
1270
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001271 /**
1272 * Return LinkProperties for the active (i.e., connected) default
1273 * network interface. It is assumed that at most one default network
1274 * is active at a time. If more than one is active, it is indeterminate
1275 * which will be returned.
1276 * @return the ip properties for the active network, or {@code null} if
1277 * none is active
1278 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001279 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001281 enforceAccessPermission();
1282 final int uid = Binder.getCallingUid();
1283 NetworkState state = getUnfilteredActiveNetworkState(uid);
1284 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001285 }
1286
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001287 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001288 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001289 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001290 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1291 if (nai != null) {
1292 synchronized (nai) {
1293 return new LinkProperties(nai.linkProperties);
1294 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001295 }
1296 return null;
1297 }
1298
Robert Greenwalt12e67352014-05-13 21:41:06 -07001299 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001300 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001301 public LinkProperties getLinkProperties(Network network) {
1302 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001303 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001304 if (nai != null) {
1305 synchronized (nai) {
1306 return new LinkProperties(nai.linkProperties);
1307 }
1308 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001309 return null;
1310 }
1311
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001312 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001313 if (nai != null) {
1314 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001315 if (nai.networkCapabilities != null) {
1316 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001317 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001318 }
1319 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001320 return null;
1321 }
1322
1323 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001324 public NetworkCapabilities getNetworkCapabilities(Network network) {
1325 enforceAccessPermission();
1326 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1327 }
1328
1329 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001330 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001331 // Require internal since we're handing out IMSI details
1332 enforceConnectivityInternalPermission();
1333
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001334 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001335 for (Network network : getAllNetworks()) {
1336 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1337 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001338 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001339 }
1340 }
1341 return result.toArray(new NetworkState[result.size()]);
1342 }
1343
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001344 @Override
1345 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1346 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001347 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001348 final long token = Binder.clearCallingIdentity();
1349 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001350 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1351 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001352 try {
1353 return mPolicyManager.getNetworkQuotaInfo(state);
1354 } catch (RemoteException e) {
1355 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001356 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001357 return null;
1358 } finally {
1359 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001360 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001361 }
1362
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001363 @Override
1364 public boolean isActiveNetworkMetered() {
1365 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001366
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001367 final NetworkInfo info = getActiveNetworkInfo();
1368 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001369 }
1370
Jeff Sharkey216c1812012-08-05 14:29:23 -07001371 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1372 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001373 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001374 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001375 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001376 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001377 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001378
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001379 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 * Ensure that a network route exists to deliver traffic to the specified
1381 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001382 * @param networkType the type of the network over which traffic to the
1383 * specified host is to be routed
1384 * @param hostAddress the IP address of the host to which the route is
1385 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 * @return {@code true} on success, {@code false} on failure
1387 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001388 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001389 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001391 if (mProtectedNetworks.contains(networkType)) {
1392 enforceConnectivityInternalPermission();
1393 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001394
Chad Brubakerc0234532014-02-14 13:24:29 -08001395 InetAddress addr;
1396 try {
1397 addr = InetAddress.getByAddress(hostAddress);
1398 } catch (UnknownHostException e) {
1399 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1400 return false;
1401 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001404 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 return false;
1406 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001407
1408 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1409 if (nai == null) {
1410 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1411 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1412 } else {
1413 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1414 }
1415 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001416 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001417
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001418 DetailedState netState;
1419 synchronized (nai) {
1420 netState = nai.networkInfo.getDetailedState();
1421 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001422
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001423 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001424 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001425 log("requestRouteToHostAddress on down network "
1426 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001427 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001428 }
1429 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001431
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001432 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001433 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001434 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001435 LinkProperties lp;
1436 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001437 synchronized (nai) {
1438 lp = nai.linkProperties;
1439 netId = nai.network.netId;
1440 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001441 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001442 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1443 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001444 } finally {
1445 Binder.restoreCallingIdentity(token);
1446 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001447 }
1448
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001449 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001450 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001451 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001452 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001453 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001454 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 if (bestRoute.getGateway().equals(addr)) {
1456 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001457 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001458 } else {
1459 // if we will connect to this through another route, add a direct route
1460 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001461 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001462 }
1463 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001464 if (DBG) log("Adding legacy route " + bestRoute +
1465 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001466 try {
1467 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1468 } catch (Exception e) {
1469 // never crash - catch them all
1470 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001471 return false;
1472 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001473 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001476 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1477 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001478 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001479 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001480 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001481 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001482 }
1483
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001484 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001485 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001486 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 if (oldRules == uidRules) return;
1488
Felipe Leme781ba142016-05-09 16:24:48 -07001489 if (uidRules == RULE_NONE) {
1490 mUidRules.delete(uid);
1491 } else {
1492 mUidRules.put(uid, uidRules);
1493 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001494 }
1495
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 // TODO: notify UID when it has requested targeted updates
1497 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001498
1499 @Override
1500 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001501 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001502 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001503 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001504 }
1505
1506 synchronized (mRulesLock) {
1507 mMeteredIfaces.clear();
1508 for (String iface : meteredIfaces) {
1509 mMeteredIfaces.add(iface);
1510 }
1511 }
1512 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001513
1514 @Override
1515 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1516 // caller is NPMS, since we only register with them
1517 if (LOGD_RULES) {
1518 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1519 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001520
1521 synchronized (mRulesLock) {
1522 mRestrictBackground = restrictBackground;
1523 }
1524
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001525 if (restrictBackground) {
1526 log("onRestrictBackgroundChanged(true): disabling tethering");
1527 mTethering.untetherAll();
1528 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001529 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001530
1531 @Override
1532 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1533 if (LOGD_RULES) {
1534 // caller is NPMS, since we only register with them
1535 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1536 + whitelisted + ")");
1537 }
1538 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001539 @Override
1540 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1541 if (LOGD_RULES) {
1542 // caller is NPMS, since we only register with them
1543 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1544 + blacklisted + ")");
1545 }
1546 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001547 };
1548
Robin Lee3b3dd942015-05-12 18:14:58 +01001549 /**
1550 * Require that the caller is either in the same user or has appropriate permission to interact
1551 * across users.
1552 *
1553 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1554 */
1555 private void enforceCrossUserPermission(int userId) {
1556 if (userId == UserHandle.getCallingUserId()) {
1557 // Not a cross-user call.
1558 return;
1559 }
1560 mContext.enforceCallingOrSelfPermission(
1561 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1562 "ConnectivityService");
1563 }
1564
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001565 private void enforceInternetPermission() {
1566 mContext.enforceCallingOrSelfPermission(
1567 android.Manifest.permission.INTERNET,
1568 "ConnectivityService");
1569 }
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001572 mContext.enforceCallingOrSelfPermission(
1573 android.Manifest.permission.ACCESS_NETWORK_STATE,
1574 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576
1577 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001578 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001581 private void enforceTetherAccessPermission() {
1582 mContext.enforceCallingOrSelfPermission(
1583 android.Manifest.permission.ACCESS_NETWORK_STATE,
1584 "ConnectivityService");
1585 }
1586
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001587 private void enforceConnectivityInternalPermission() {
1588 mContext.enforceCallingOrSelfPermission(
1589 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1590 "ConnectivityService");
1591 }
1592
Hugo Benichi514da602016-07-19 15:59:27 +09001593 private void enforceConnectivityRestrictedNetworksPermission() {
1594 try {
1595 mContext.enforceCallingOrSelfPermission(
1596 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1597 "ConnectivityService");
1598 return;
1599 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1600 enforceConnectivityInternalPermission();
1601 }
1602
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001603 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001604 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001605 }
1606
Lorenzo Colitti18660282016-07-04 12:55:44 +09001607 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001608 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001609 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001610 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001611 }
1612
1613 private void sendInetConditionBroadcast(NetworkInfo info) {
1614 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1615 }
1616
Wink Saville628b0852011-08-04 15:01:58 -07001617 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001618 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001619 info = new NetworkInfo(info);
1620 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001621 }
1622
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001623 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001624 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001625 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 if (info.isFailover()) {
1627 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1628 info.setFailover(false);
1629 }
1630 if (info.getReason() != null) {
1631 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1632 }
1633 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001634 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1635 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001637 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001638 return intent;
1639 }
1640
1641 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1642 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1643 }
1644
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001645 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001646 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1647 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1648 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001649 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001650 final long ident = Binder.clearCallingIdentity();
1651 try {
1652 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1653 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1654 } finally {
1655 Binder.restoreCallingIdentity(ident);
1656 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001657 }
1658
Mike Lockwood0f79b542009-08-14 14:18:49 -04001659 private void sendStickyBroadcast(Intent intent) {
1660 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001661 if (!mSystemReady) {
1662 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001663 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001665 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001666 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001667 }
1668
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001669 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001670 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001671 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001672 final NetworkInfo ni = intent.getParcelableExtra(
1673 ConnectivityManager.EXTRA_NETWORK_INFO);
1674 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1675 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1676 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001677 } else {
1678 BroadcastOptions opts = BroadcastOptions.makeBasic();
1679 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1680 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001681 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001682 final IBatteryStats bs = BatteryStatsService.getService();
1683 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001684 bs.noteConnectivityChanged(intent.getIntExtra(
1685 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1686 ni != null ? ni.getState().toString() : "?");
1687 } catch (RemoteException e) {
1688 }
1689 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001690 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001691 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001692 } finally {
1693 Binder.restoreCallingIdentity(ident);
1694 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001695 }
1696 }
1697
1698 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001699 loadGlobalProxy();
1700
Mike Lockwood0f79b542009-08-14 14:18:49 -04001701 synchronized(this) {
1702 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001703 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001704 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001705 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001706 }
1707 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001708 // load the global proxy at startup
1709 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001710
Robin Lee244ce8e2016-01-05 18:03:46 +00001711 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1712 // for user to unlock device too.
1713 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001714
Erik Klineda4bfa82015-04-30 12:58:40 +09001715 // Configure whether mobile data is always on.
1716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1717
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001718 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001719
1720 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001724 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001725 *
1726 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001727 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001728 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001729 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1730 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001731
1732 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001734
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 if (networkAgent.networkCapabilities.hasTransport(
1736 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001737 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1738 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001739 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001740 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001741 } else if (networkAgent.networkCapabilities.hasTransport(
1742 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001743 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1744 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001745 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001747 } else {
1748 // do not track any other networks
1749 timeout = 0;
1750 }
1751
Robert Greenwalt7b816022014-04-18 15:25:25 -07001752 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001753 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001754 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001755 } catch (Exception e) {
1756 // You shall not crash!
1757 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001758 }
1759 }
1760 }
1761
1762 /**
1763 * Remove data activity tracking when network disconnects.
1764 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001765 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1766 final String iface = networkAgent.linkProperties.getInterfaceName();
1767 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001768
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1770 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001771 try {
1772 // the call fails silently if no idletimer setup for this interface
1773 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001774 } catch (Exception e) {
1775 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001776 }
1777 }
1778 }
1779
1780 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001781 * Reads the network specific MTU size from reources.
1782 * and set it on it's iface.
1783 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1785 final String iface = newLp.getInterfaceName();
1786 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001787 if (oldLp == null && mtu == 0) {
1788 // Silently ignore unset MTU value.
1789 return;
1790 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1792 if (VDBG) log("identical MTU - not setting");
1793 return;
1794 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001795 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001796 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001797 return;
1798 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001799
w1997615afd812014-08-05 15:18:11 -07001800 // Cannot set MTU without interface name
1801 if (TextUtils.isEmpty(iface)) {
1802 loge("Setting MTU size with null iface.");
1803 return;
1804 }
1805
Robert Greenwalt7b816022014-04-18 15:25:25 -07001806 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001807 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001808 mNetd.setMtu(iface, mtu);
1809 } catch (Exception e) {
1810 Slog.e(TAG, "exception in setMtu()" + e);
1811 }
1812 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001813
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001814 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001815 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1816
1817 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001818 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001819 protected int getDefaultTcpRwnd() {
1820 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1821 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001822
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001823 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1824 if (isDefaultNetwork(nai) == false) {
1825 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001826 }
1827
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001828 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1829 String[] values = null;
1830 if (tcpBufferSizes != null) {
1831 values = tcpBufferSizes.split(",");
1832 }
1833
1834 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001835 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001836 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1837 values = tcpBufferSizes.split(",");
1838 }
1839
1840 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1841
1842 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001843 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001844
1845 final String prefix = "/sys/kernel/ipv4/tcp_";
1846 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1847 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1848 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1849 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1850 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1851 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1852 mCurrentTcpBufferSizes = tcpBufferSizes;
1853 } catch (IOException e) {
1854 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001855 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001857 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001858 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001859 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1860 if (rwndValue != 0) {
1861 SystemProperties.set(sysctlKey, rwndValue.toString());
1862 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001863 }
1864
Mattias Falk8b47b362011-08-23 14:15:13 +02001865 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001866 /*
1867 * Tell the VMs to toss their DNS caches
1868 */
1869 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1870 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001871 /*
1872 * Connectivity events can happen before boot has completed ...
1873 */
1874 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001875 final long ident = Binder.clearCallingIdentity();
1876 try {
1877 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1878 } finally {
1879 Binder.restoreCallingIdentity(ident);
1880 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001881 }
1882
Robert Greenwalt562cc542014-05-15 18:07:26 -07001883 @Override
1884 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1886 NETWORK_RESTORE_DELAY_PROP_NAME);
1887 if(restoreDefaultNetworkDelayStr != null &&
1888 restoreDefaultNetworkDelayStr.length() != 0) {
1889 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001890 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 } catch (NumberFormatException e) {
1892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001894 // if the system property isn't set, use the value for the apn type
1895 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1896
1897 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1898 (mNetConfigs[networkType] != null)) {
1899 ret = mNetConfigs[networkType].restoreTime;
1900 }
1901 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001904 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001905 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001906 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001907 }
1908 return false;
1909 }
1910
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001911 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1912 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1913 final long DIAG_TIME_MS = 5000;
1914 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1915 // Start gathering diagnostic information.
1916 netDiags.add(new NetworkDiagnostics(
1917 nai.network,
1918 new LinkProperties(nai.linkProperties), // Must be a copy.
1919 DIAG_TIME_MS));
1920 }
1921
1922 for (NetworkDiagnostics netDiag : netDiags) {
1923 pw.println();
1924 netDiag.waitForMeasurements();
1925 netDiag.dump(pw);
1926 }
1927 }
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001930 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1931 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001932 if (mContext.checkCallingOrSelfPermission(
1933 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001935 pw.println("Permission Denial: can't dump ConnectivityService " +
1936 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1937 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 return;
1939 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001940
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001941 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942 dumpNetworkDiagnostics(pw);
1943 return;
1944 }
Erik Kline379747a2015-06-05 17:47:34 +09001945
Lorenzo Colittie3805462015-06-03 11:18:24 +09001946 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001947 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001948 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001949 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001950 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001951 pw.println();
1952
Paul Jensen85cf78e2015-06-25 13:25:07 -04001953 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001954 pw.print("Active default network: ");
1955 if (defaultNai == null) {
1956 pw.println("none");
1957 } else {
1958 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001960 pw.println();
1961
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001962 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001963 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001964 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1965 pw.println(nai.toString());
1966 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001967 pw.println(String.format(
1968 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1969 nai.numForegroundNetworkRequests(),
1970 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1971 nai.numBackgroundNetworkRequests(),
1972 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001974 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1975 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001976 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001977 pw.decreaseIndent();
1978 pw.println("Lingered:");
1979 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001980 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 pw.decreaseIndent();
1982 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001983 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001984 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001986
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001987 pw.println("Metered Interfaces:");
1988 pw.increaseIndent();
1989 for (String value : mMeteredIfaces) {
1990 pw.println(value);
1991 }
1992 pw.decreaseIndent();
1993 pw.println();
1994
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001995 pw.print("Restrict background: ");
1996 pw.println(mRestrictBackground);
1997 pw.println();
1998
Felipe Leme46c4fc32016-05-04 09:21:43 -07001999 pw.println("Status for known UIDs:");
2000 pw.increaseIndent();
2001 final int size = mUidRules.size();
2002 for (int i = 0; i < size; i++) {
2003 final int uid = mUidRules.keyAt(i);
2004 pw.print("UID=");
2005 pw.print(uid);
2006 final int uidRules = mUidRules.get(uid, RULE_NONE);
2007 pw.print(" rules=");
2008 pw.print(uidRulesToString(uidRules));
2009 pw.println();
2010 }
2011 pw.println();
2012 pw.decreaseIndent();
2013
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002014 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002015 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002016 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2017 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002018 }
2019 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002020 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002021
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002022 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002023
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002024 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002025 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002026
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002027 pw.println();
2028 mKeepaliveTracker.dump(pw);
2029
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002030 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002031 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002032
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002033 if (argsContain(args, "--short") == false) {
2034 pw.println();
2035 synchronized (mValidationLogs) {
2036 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002037 for (ValidationLog p : mValidationLogs) {
2038 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002039 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002040 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002041 pw.decreaseIndent();
2042 }
2043 }
Erik Kline7523eb32015-07-09 18:24:03 +09002044
2045 pw.println();
2046 pw.println("mNetworkRequestInfoLogs (most recent first):");
2047 pw.increaseIndent();
2048 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2049 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002050
2051 pw.println();
2052 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2053 pw.increaseIndent();
2054 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2055 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002056
2057 pw.println();
2058 pw.println("NetTransition WakeLock activity (most recent first):");
2059 pw.increaseIndent();
2060 mWakelockLogs.reverseDump(fd, pw, args);
2061 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002065 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002066 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002067 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002068 if (officialNai != null && officialNai.equals(nai)) return true;
2069 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002070 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002071 " - " + nai);
2072 }
2073 return false;
2074 }
2075
Robert Greenwalt42acef32009-08-12 16:08:25 -07002076 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002077 private class NetworkStateTrackerHandler extends Handler {
2078 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002079 super(looper);
2080 }
2081
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002082 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002084 default:
2085 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002086 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002087 handleAsyncChannelHalfConnect(msg);
2088 break;
2089 }
2090 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2091 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2092 if (nai != null) nai.asyncChannel.disconnect();
2093 break;
2094 }
2095 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2096 handleAsyncChannelDisconnected(msg);
2097 break;
2098 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002099 }
2100 return true;
2101 }
2102
2103 private void maybeHandleNetworkAgentMessage(Message msg) {
2104 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2105 if (nai == null) {
2106 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002107 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 }
2109 return;
2110 }
2111
2112 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2115 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002116 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2117 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002118 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002119 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002120 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002121 break;
2122 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002124 if (VDBG) {
2125 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002126 "; created=" + nai.created +
2127 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 LinkProperties oldLp = nai.linkProperties;
2130 synchronized (nai) {
2131 nai.linkProperties = (LinkProperties)msg.obj;
2132 }
Robin Lee585e2482016-05-01 23:00:00 +01002133 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 break;
2135 }
2136 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002137 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 updateNetworkInfo(nai, info);
2139 break;
2140 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002141 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002142 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002143 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 break;
2145 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002146 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002147 try {
2148 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002149 } catch (Exception e) {
2150 // Never crash!
2151 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002152 }
2153 break;
2154 }
2155 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002156 try {
2157 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002158 } catch (Exception e) {
2159 // Never crash!
2160 loge("Exception in removeVpnUidRanges: " + e);
2161 }
2162 break;
2163 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002164 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002165 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2166 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002167 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002168 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002169 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002170 break;
2171 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002172 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002173 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2174 break;
2175 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002176 }
2177 }
2178
2179 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2180 switch (msg.what) {
2181 default:
2182 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002183 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002184 final NetworkAgentInfo nai;
2185 synchronized (mNetworkForNetId) {
2186 nai = mNetworkForNetId.get(msg.arg2);
2187 }
2188 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002189 final boolean valid =
2190 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002191 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002192 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2193 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002194 if (valid != nai.lastValidated) {
2195 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002196 nai.lastValidated = valid;
2197 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002198 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002199 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2200 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002201 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002202 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002203 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002204 Bundle redirectUrlBundle = new Bundle();
2205 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002206 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002207 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002208 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002209 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002210 if (wasValidated && !nai.lastValidated) {
2211 handleNetworkUnvalidated(nai);
2212 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002213 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 break;
2215 }
Paul Jensen869868be2014-05-15 10:33:05 -04002216 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002217 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002218 final boolean visible = (msg.arg1 != 0);
2219 final NetworkAgentInfo nai;
2220 synchronized (mNetworkForNetId) {
2221 nai = mNetworkForNetId.get(netId);
2222 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002223 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002224 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002225 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002226 nai.lastCaptivePortalDetected = visible;
2227 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002228 if (nai.lastCaptivePortalDetected &&
2229 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2230 if (DBG) log("Avoiding captive portal network: " + nai.name());
2231 nai.asyncChannel.sendMessage(
2232 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2233 teardownUnneededNetwork(nai);
2234 break;
2235 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002236 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002237 }
2238 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002239 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002240 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002241 if (nai == null) {
2242 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2243 break;
2244 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002245 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002246 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002247 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002248 }
Paul Jensen869868be2014-05-15 10:33:05 -04002249 }
Paul Jensen869868be2014-05-15 10:33:05 -04002250 break;
2251 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002252 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002253 return true;
2254 }
2255
Calvin On1f64f3f2016-10-11 15:10:46 -07002256 private int getCaptivePortalMode() {
2257 return Settings.Global.getInt(mContext.getContentResolver(),
2258 Settings.Global.CAPTIVE_PORTAL_MODE,
2259 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2260 }
2261
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002262 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2263 switch (msg.what) {
2264 default:
2265 return false;
2266 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2267 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2268 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2269 handleLingerComplete(nai);
2270 }
2271 break;
2272 }
2273 }
2274 return true;
2275 }
2276
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002277 @Override
2278 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002279 if (!maybeHandleAsyncChannelMessage(msg) &&
2280 !maybeHandleNetworkMonitorMessage(msg) &&
2281 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002282 maybeHandleNetworkAgentMessage(msg);
2283 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002284 }
2285 }
2286
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002287 private void updateLingerState(NetworkAgentInfo nai, long now) {
2288 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2289 // 2. If the network was lingering and there are now requests, unlinger it.
2290 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2291 // one lingered request, start lingering.
2292 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002293 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 if (DBG) log("Unlingering " + nai.name());
2295 nai.unlinger();
2296 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002297 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002298 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002299 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002300 nai.linger();
2301 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2302 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2303 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002304 }
2305
Robert Greenwalt7b816022014-04-18 15:25:25 -07002306 private void handleAsyncChannelHalfConnect(Message msg) {
2307 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002308 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002309 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2310 if (VDBG) log("NetworkFactory connected");
2311 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002312 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002313 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002314 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002315 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002316 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 }
2318 } else {
2319 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002320 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002321 }
2322 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2323 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2324 if (VDBG) log("NetworkAgent connected");
2325 // A network agent has requested a connection. Establish the connection.
2326 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2327 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2328 } else {
2329 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002330 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002331 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002332 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002333 synchronized (mNetworkForNetId) {
2334 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002335 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002336 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002337 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002338 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002339 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002340 }
2341 }
2342 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002343
Robert Greenwalt7b816022014-04-18 15:25:25 -07002344 private void handleAsyncChannelDisconnected(Message msg) {
2345 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2346 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002348 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002349 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002350 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002351 // TODO - if we move the logic to the network agent (have them disconnect
2352 // because they lost all their requests or because their score isn't good)
2353 // then they would disconnect organically, report their new state and then
2354 // disconnect the channel.
2355 if (nai.networkInfo.isConnected()) {
2356 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2357 null, null);
2358 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002359 final boolean wasDefault = isDefaultNetwork(nai);
2360 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002361 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002362 // Log default network disconnection before required book-keeping.
2363 // Let rematchAllNetworksAndRequests() below record a new default network event
2364 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2365 // whose timestamps tell how long it takes to recover a default network.
2366 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002367 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002368 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002369 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2370 // by other networks that are already connected. Perhaps that can be done by
2371 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2372 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002374 mKeepaliveTracker.handleStopAllKeepalives(nai,
2375 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002376 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002377 mNetworkAgentInfos.remove(msg.replyTo);
2378 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002379 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002380 // Remove the NetworkAgent, but don't mark the netId as
2381 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002382 mNetworkForNetId.remove(nai.network.netId);
2383 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002384 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002385 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2386 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002387 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2388 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2389 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002390 sendUpdatedScoreToFactories(request, 0);
2391 }
2392 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002393 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002394 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002396 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002397 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002398 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002399 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002400 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002401 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002402 if (nai.created) {
2403 // Tell netd to clean up the configuration for this network
2404 // (routing rules, DNS, etc).
2405 // This may be slow as it requires a lot of netd shelling out to ip and
2406 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2407 // after we've rematched networks with requests which should make a potential
2408 // fallback network the default or requested a new network from the
2409 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2410 // long time.
2411 try {
2412 mNetd.removeNetwork(nai.network.netId);
2413 } catch (Exception e) {
2414 loge("Exception removing network: " + e);
2415 }
2416 }
2417 synchronized (mNetworkForNetId) {
2418 mNetIdInUse.delete(nai.network.netId);
2419 }
2420 } else {
2421 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2422 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002423 }
2424 }
2425
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002426 // If this method proves to be too slow then we can maintain a separate
2427 // pendingIntent => NetworkRequestInfo map.
2428 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2429 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2430 Intent intent = pendingIntent.getIntent();
2431 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2432 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2433 if (existingPendingIntent != null &&
2434 existingPendingIntent.getIntent().filterEquals(intent)) {
2435 return entry.getValue();
2436 }
2437 }
2438 return null;
2439 }
2440
2441 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2442 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2443
2444 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2445 if (existingRequest != null) { // remove the existing request.
2446 if (DBG) log("Replacing " + existingRequest.request + " with "
2447 + nri.request + " because their intents matched.");
2448 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2449 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002450 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002451 }
2452
Erik Klineda4bfa82015-04-30 12:58:40 +09002453 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002454 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002455 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002456 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002457 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002458 if (nri.request.networkCapabilities.hasSignalStrength() &&
2459 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2460 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002461 }
2462 }
2463 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002464 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002465 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002466 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002467 }
2468 }
2469
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002470 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2471 int callingUid) {
2472 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2473 if (nri != null) {
2474 handleReleaseNetworkRequest(nri.request, callingUid);
2475 }
2476 }
2477
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002478 // Determines whether the network is the best (or could become the best, if it validated), for
2479 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2480 // on the value of reason:
2481 //
2482 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2483 // then it should be torn down.
2484 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2485 // then it should be lingered.
2486 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2487 final int numRequests;
2488 switch (reason) {
2489 case TEARDOWN:
2490 numRequests = nai.numRequestNetworkRequests();
2491 break;
2492 case LINGER:
2493 numRequests = nai.numForegroundNetworkRequests();
2494 break;
2495 default:
2496 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2497 return true;
2498 }
2499
2500 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002501 return false;
2502 }
Paul Jensene0988542015-06-25 15:30:08 -04002503 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002504 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2505 // Background requests don't affect lingering.
2506 continue;
2507 }
2508
Paul Jensene0988542015-06-25 15:30:08 -04002509 // If this Network is already the highest scoring Network for a request, or if
2510 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002511 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002512 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002513 // Note that this catches two important cases:
2514 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2515 // is currently satisfying the request. This is desirable when
2516 // cellular ends up validating but WiFi does not.
2517 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002518 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002519 // WiFi ends up validating and out scoring cellular.
2520 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2521 nai.getCurrentScoreAsValidated())) {
2522 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002523 }
2524 }
Paul Jensene0988542015-06-25 15:30:08 -04002525 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002526 }
2527
Erik Klineacdd6392016-07-07 16:50:58 +09002528 private NetworkRequestInfo getNriForAppRequest(
2529 NetworkRequest request, int callingUid, String requestedOperation) {
2530 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2531
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002533 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002534 log(String.format("UID %d attempted to %s for unowned request %s",
2535 callingUid, requestedOperation, nri));
2536 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002537 }
Erik Klineacdd6392016-07-07 16:50:58 +09002538 }
2539
2540 return nri;
2541 }
2542
Erik Kline3841a482015-11-25 12:49:38 +09002543 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2544 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2545 nri.request.requestId) == null) {
2546 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2547 }
2548 }
2549
Erik Klineacdd6392016-07-07 16:50:58 +09002550 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2551 final NetworkRequestInfo nri = getNriForAppRequest(
2552 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002553 if (nri != null) {
2554 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2555 }
2556 }
Erik Klineacdd6392016-07-07 16:50:58 +09002557
Erik Kline3841a482015-11-25 12:49:38 +09002558 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2559 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2560 if (VDBG || (DBG && nri.request.isRequest())) {
2561 log("releasing " + nri.request + " (" + logCallbackType + ")");
2562 }
Erik Klineacdd6392016-07-07 16:50:58 +09002563 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002564 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002565 synchronized (mUidToNetworkRequestCount) {
2566 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2567 if (requests < 1) {
2568 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2569 nri.mUid);
2570 } else if (requests == 1) {
2571 mUidToNetworkRequestCount.removeAt(
2572 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2573 } else {
2574 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2575 }
2576 }
2577 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2578 if (nri.request.isRequest()) {
2579 boolean wasKept = false;
2580 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2581 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002582 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002583 nai.removeRequest(nri.request.requestId);
2584 if (VDBG) {
2585 log(" Removing from current network " + nai.name() +
2586 ", leaving " + nai.numNetworkRequests() + " requests.");
2587 }
2588 // If there are still lingered requests on this network, don't tear it down,
2589 // but resume lingering instead.
2590 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002591 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002592 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2593 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002594 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002595 wasKept = true;
2596 }
2597 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002598 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2599 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002600 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002601 }
Erik Klineacdd6392016-07-07 16:50:58 +09002602 }
2603
2604 // TODO: remove this code once we know that the Slog.wtf is never hit.
2605 //
2606 // Find all networks that are satisfying this request and remove the request
2607 // from their request lists.
2608 // TODO - it's my understanding that for a request there is only a single
2609 // network satisfying it, so this loop is wasteful
2610 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2611 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2612 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2613 otherNai.name() + ", but mNetworkAgentInfos says " +
2614 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002615 }
2616 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002617
Erik Klineacdd6392016-07-07 16:50:58 +09002618 // Maintain the illusion. When this request arrived, we might have pretended
2619 // that a network connected to serve it, even though the network was already
2620 // connected. Now that this request has gone away, we might have to pretend
2621 // that the network disconnected. LegacyTypeTracker will generate that
2622 // phantom disconnect for this type.
2623 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2624 boolean doRemove = true;
2625 if (wasKept) {
2626 // check if any of the remaining requests for this network are for the
2627 // same legacy type - if so, don't remove the nai
2628 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2629 NetworkRequest otherRequest = nai.requestAt(i);
2630 if (otherRequest.legacyType == nri.request.legacyType &&
2631 otherRequest.isRequest()) {
2632 if (DBG) log(" still have other legacy request - leaving");
2633 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002634 }
2635 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002636 }
2637
Erik Klineacdd6392016-07-07 16:50:58 +09002638 if (doRemove) {
2639 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002640 }
2641 }
Erik Klineacdd6392016-07-07 16:50:58 +09002642
2643 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2644 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2645 nri.request);
2646 }
2647 } else {
2648 // listens don't have a singular affectedNetwork. Check all networks to see
2649 // if this listen request applies and remove it.
2650 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2651 nai.removeRequest(nri.request.requestId);
2652 if (nri.request.networkCapabilities.hasSignalStrength() &&
2653 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2654 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2655 }
2656 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002657 }
Erik Kline3841a482015-11-25 12:49:38 +09002658 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002659 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002660
Lorenzo Colitti18660282016-07-04 12:55:44 +09002661 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002662 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2663 enforceConnectivityInternalPermission();
2664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2665 accept ? 1 : 0, always ? 1: 0, network));
2666 }
2667
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002668 @Override
2669 public void setAvoidUnvalidated(Network network) {
2670 enforceConnectivityInternalPermission();
2671 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2672 }
2673
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002674 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2675 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2676 " accept=" + accept + " always=" + always);
2677
2678 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2679 if (nai == null) {
2680 // Nothing to do.
2681 return;
2682 }
2683
2684 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002685 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002686 return;
2687 }
2688
2689 if (!nai.networkMisc.explicitlySelected) {
2690 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2691 }
2692
2693 if (accept != nai.networkMisc.acceptUnvalidated) {
2694 int oldScore = nai.getCurrentScore();
2695 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002696 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002697 sendUpdatedScoreToFactories(nai);
2698 }
2699
2700 if (always) {
2701 nai.asyncChannel.sendMessage(
2702 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2703 }
2704
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002705 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002706 // Tell the NetworkAgent to not automatically reconnect to the network.
2707 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2708 // Teardown the nework.
2709 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002710 }
2711
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002712 }
2713
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002714 private void handleSetAvoidUnvalidated(Network network) {
2715 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2716 if (nai == null || nai.lastValidated) {
2717 // Nothing to do. The network either disconnected or revalidated.
2718 return;
2719 }
2720 if (!nai.avoidUnvalidated) {
2721 int oldScore = nai.getCurrentScore();
2722 nai.avoidUnvalidated = true;
2723 rematchAllNetworksAndRequests(nai, oldScore);
2724 sendUpdatedScoreToFactories(nai);
2725 }
2726 }
2727
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002728 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002729 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 mHandler.sendMessageDelayed(
2731 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2732 PROMPT_UNVALIDATED_DELAY_MS);
2733 }
2734
Hugo Benichic8e9e122016-09-14 23:23:08 +00002735 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002736 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002737 }
2738
Erik Kline065ab6e2016-10-02 18:02:14 +09002739 private void rematchForAvoidBadWifiUpdate() {
2740 rematchAllNetworksAndRequests(null, 0);
2741 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2742 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2743 sendUpdatedScoreToFactories(nai);
2744 }
2745 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002746 }
2747
Erik Kline065ab6e2016-10-02 18:02:14 +09002748 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002749 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002750 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002751 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002752 if (!configRestrict) {
2753 pw.println("Bad Wi-Fi avoidance: unrestricted");
2754 return;
2755 }
2756
2757 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2758 pw.increaseIndent();
2759 pw.println("Config restrict: " + configRestrict);
2760
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002761 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002762 String description;
2763 // Can't use a switch statement because strings are legal case labels, but null is not.
2764 if ("0".equals(value)) {
2765 description = "get stuck";
2766 } else if (value == null) {
2767 description = "prompt";
2768 } else if ("1".equals(value)) {
2769 description = "avoid";
2770 } else {
2771 description = value + " (?)";
2772 }
2773 pw.println("User setting: " + description);
2774 pw.println("Network overrides:");
2775 pw.increaseIndent();
2776 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2777 if (nai.avoidUnvalidated) {
2778 pw.println(nai.name());
2779 }
2780 }
2781 pw.decreaseIndent();
2782 pw.decreaseIndent();
2783 }
2784
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002785 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2786 final String action;
2787 switch (type) {
2788 case NO_INTERNET:
2789 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2790 break;
2791 case LOST_INTERNET:
2792 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2793 break;
2794 default:
2795 Slog.wtf(TAG, "Unknown notification type " + type);
2796 return;
2797 }
2798
2799 Intent intent = new Intent(action);
2800 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2801 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2802 intent.setClassName("com.android.settings",
2803 "com.android.settings.wifi.WifiNoInternetDialog");
2804
2805 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2806 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2807 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2808 }
2809
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002810 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002811 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002812 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2813
2814 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2815 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002816 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002817 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002818 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2819 return;
2820 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002821 showValidationNotification(nai, NotificationType.NO_INTERNET);
2822 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002823
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002824 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2825 NetworkCapabilities nc = nai.networkCapabilities;
2826 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002827
Erik Kline065ab6e2016-10-02 18:02:14 +09002828 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002829 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002830 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2831 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832 }
2833
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002834 private class InternalHandler extends Handler {
2835 public InternalHandler(Looper looper) {
2836 super(looper);
2837 }
2838
2839 @Override
2840 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002841 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002842 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002843 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002844 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002845 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002846 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002847 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002849 break;
2850 }
Jason Monkdecd2952013-10-10 14:02:51 -04002851 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002852 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002853 break;
2854 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002855 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002856 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2857 break;
2858 }
2859 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2860 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002861 break;
2862 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002863 case EVENT_REGISTER_NETWORK_AGENT: {
2864 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2865 break;
2866 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002867 case EVENT_REGISTER_NETWORK_REQUEST:
2868 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002869 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002870 break;
2871 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002872 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2873 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002874 handleRegisterNetworkRequestWithIntent(msg);
2875 break;
2876 }
Erik Kline3841a482015-11-25 12:49:38 +09002877 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2878 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2879 handleTimedOutNetworkRequest(nri);
2880 break;
2881 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002882 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2883 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2884 break;
2885 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002886 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002887 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002888 break;
2889 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002890 case EVENT_SET_ACCEPT_UNVALIDATED: {
2891 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2892 break;
2893 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002894 case EVENT_SET_AVOID_UNVALIDATED: {
2895 handleSetAvoidUnvalidated((Network) msg.obj);
2896 break;
2897 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002898 case EVENT_PROMPT_UNVALIDATED: {
2899 handlePromptUnvalidated((Network) msg.obj);
2900 break;
2901 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002902 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2903 handleMobileDataAlwaysOn();
2904 break;
2905 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002906 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2907 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2908 mKeepaliveTracker.handleStartKeepalive(msg);
2909 break;
2910 }
2911 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2912 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2913 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2914 int slot = msg.arg1;
2915 int reason = msg.arg2;
2916 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2917 break;
2918 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002919 case EVENT_SYSTEM_READY: {
2920 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2921 nai.networkMonitor.systemReady = true;
2922 }
2923 break;
2924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
2927 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002928
2929 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002930 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002931 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002932 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002933 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002934 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002935 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002936 } else {
2937 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2938 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002939 }
2940
2941 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002942 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002943 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002944 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002945
2946 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002947 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002948 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002949 } else {
2950 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2951 }
2952 }
2953
2954 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002955 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002956 public int getLastTetherError(String iface) {
2957 enforceTetherAccessPermission();
2958
2959 if (isTetheringSupported()) {
2960 return mTethering.getLastTetherError(iface);
2961 } else {
2962 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2963 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002964 }
2965
2966 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002967 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002968 public String[] getTetherableUsbRegexs() {
2969 enforceTetherAccessPermission();
2970 if (isTetheringSupported()) {
2971 return mTethering.getTetherableUsbRegexs();
2972 } else {
2973 return new String[0];
2974 }
2975 }
2976
Lorenzo Colitti18660282016-07-04 12:55:44 +09002977 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002978 public String[] getTetherableWifiRegexs() {
2979 enforceTetherAccessPermission();
2980 if (isTetheringSupported()) {
2981 return mTethering.getTetherableWifiRegexs();
2982 } else {
2983 return new String[0];
2984 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002985 }
2986
Lorenzo Colitti18660282016-07-04 12:55:44 +09002987 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002988 public String[] getTetherableBluetoothRegexs() {
2989 enforceTetherAccessPermission();
2990 if (isTetheringSupported()) {
2991 return mTethering.getTetherableBluetoothRegexs();
2992 } else {
2993 return new String[0];
2994 }
2995 }
2996
Lorenzo Colitti18660282016-07-04 12:55:44 +09002997 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002998 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002999 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003000 if (isTetheringSupported()) {
3001 return mTethering.setUsbTethering(enable);
3002 } else {
3003 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3004 }
3005 }
3006
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003007 // TODO - move iface listing, queries, etc to new module
3008 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003009 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003010 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003011 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003012 return mTethering.getTetherableIfaces();
3013 }
3014
Lorenzo Colitti18660282016-07-04 12:55:44 +09003015 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003016 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003018 return mTethering.getTetheredIfaces();
3019 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003020
Lorenzo Colitti18660282016-07-04 12:55:44 +09003021 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003022 public String[] getTetheringErroredIfaces() {
3023 enforceTetherAccessPermission();
3024 return mTethering.getErroredIfaces();
3025 }
3026
Lorenzo Colitti18660282016-07-04 12:55:44 +09003027 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003028 public String[] getTetheredDhcpRanges() {
3029 enforceConnectivityInternalPermission();
3030 return mTethering.getTetheredDhcpRanges();
3031 }
3032
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003033 // if ro.tether.denied = true we default to no tethering
3034 // gservices could set the secure setting to 1 though to enable it on a build where it
3035 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003036 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003037 public boolean isTetheringSupported() {
3038 enforceTetherAccessPermission();
3039 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003040 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003041 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3042 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003043 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
Erik Klined781fba2017-01-23 13:01:58 +09003044 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003045 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003046
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003047 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003048 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003049 ConnectivityManager.enforceTetherChangePermission(mContext);
3050 if (!isTetheringSupported()) {
3051 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3052 return;
3053 }
3054 mTethering.startTethering(type, receiver, showProvisioningUi);
3055 }
3056
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003057 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003058 public void stopTethering(int type) {
3059 ConnectivityManager.enforceTetherChangePermission(mContext);
3060 mTethering.stopTethering(type);
3061 }
3062
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003063 // Called when we lose the default network and have no replacement yet.
3064 // This will automatically be cleared after X seconds or a new default network
3065 // becomes CONNECTED, whichever happens first. The timer is started by the
3066 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003067 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003068 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003069 if (mNetTransitionWakeLock.isHeld()) {
3070 return;
3071 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003072 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003073 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003074 mWakelockLogs.log("ACQUIRE for " + forWhom);
3075 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3076 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003077 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003078
Hugo Benichi4c31b342017-03-30 23:18:10 +09003079 // Called when we gain a new default network to release the network transition wakelock in a
3080 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3081 // message is cancelled.
3082 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003083 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003084 if (!mNetTransitionWakeLock.isHeld()) {
3085 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003086 }
3087 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003088 // Cancel self timeout on wakelock hold.
3089 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3090 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3091 mHandler.sendMessageDelayed(msg, 1000);
3092 }
3093
3094 // Called when either message of ensureNetworkTransitionWakelock or
3095 // scheduleReleaseNetworkTransitionWakelock is processed.
3096 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3097 String event = eventName(eventId);
3098 synchronized (this) {
3099 if (!mNetTransitionWakeLock.isHeld()) {
3100 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3101 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3102 return;
3103 }
3104 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003105 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003106 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003107 }
3108
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003109 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003110 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003111 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003112 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003113 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003114 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003115 }
3116
Lorenzo Colitti18660282016-07-04 12:55:44 +09003117 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003118 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003119 enforceAccessPermission();
3120 enforceInternetPermission();
3121
Paul Jensenbfd17b72015-04-07 12:43:13 -04003122 NetworkAgentInfo nai;
3123 if (network == null) {
3124 nai = getDefaultNetwork();
3125 } else {
3126 nai = getNetworkAgentInfoForNetwork(network);
3127 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003128 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3129 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3130 return;
3131 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003132 // Revalidate if the app report does not match our current validated state.
3133 if (hasConnectivity == nai.lastValidated) return;
3134 final int uid = Binder.getCallingUid();
3135 if (DBG) {
3136 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3137 ") by " + uid);
3138 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003139 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003140 // Validating a network that has not yet connected could result in a call to
3141 // rematchNetworkAndRequests() which is not meant to work on such networks.
3142 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003143
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003144 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003145
3146 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3147 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003148 }
3149
Paul Jensencee9b512015-05-06 07:32:40 -04003150 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003151 // this information is already available as a world read/writable jvm property
3152 // so this API change wouldn't have a benifit. It also breaks the passing
3153 // of proxy info to all the JVMs.
3154 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003155 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003156 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003157 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3158 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003159 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003160 }
3161
Lorenzo Colitti18660282016-07-04 12:55:44 +09003162 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003163 public ProxyInfo getProxyForNetwork(Network network) {
3164 if (network == null) return getDefaultProxy();
3165 final ProxyInfo globalProxy = getGlobalProxy();
3166 if (globalProxy != null) return globalProxy;
3167 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3168 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3169 // caller may not have.
3170 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3171 if (nai == null) return null;
3172 synchronized (nai) {
3173 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3174 if (proxyInfo == null) return null;
3175 return new ProxyInfo(proxyInfo);
3176 }
3177 }
3178
Paul Jensene0bef712014-12-10 15:12:18 -05003179 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3180 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3181 // proxy is null then there is no proxy in place).
3182 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3183 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3184 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3185 proxy = null;
3186 }
3187 return proxy;
3188 }
3189
3190 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3191 // better for determining if a new proxy broadcast is necessary:
3192 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3193 // avoid unnecessary broadcasts.
3194 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3195 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3196 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3197 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3198 // all set.
3199 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3200 a = canonicalizeProxyInfo(a);
3201 b = canonicalizeProxyInfo(b);
3202 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3203 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3204 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3205 }
3206
Jason Monk207900c2014-04-25 15:00:09 -04003207 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003208 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003209
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003210 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003211 if (proxyProperties == mGlobalProxy) return;
3212 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3213 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3214
3215 String host = "";
3216 int port = 0;
3217 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003218 String pacFileUrl = "";
3219 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003220 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003221 if (!proxyProperties.isValid()) {
3222 if (DBG)
3223 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3224 return;
3225 }
Jason Monk207900c2014-04-25 15:00:09 -04003226 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003227 host = mGlobalProxy.getHost();
3228 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003229 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003230 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003231 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003232 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003233 } else {
3234 mGlobalProxy = null;
3235 }
3236 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003237 final long token = Binder.clearCallingIdentity();
3238 try {
3239 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3240 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3241 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3242 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003243 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003244 } finally {
3245 Binder.restoreCallingIdentity(token);
3246 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003247
Jason Monkcf0f97a2014-10-02 15:39:38 -04003248 if (mGlobalProxy == null) {
3249 proxyProperties = mDefaultProxy;
3250 }
3251 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003253 }
3254
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003255 private void loadGlobalProxy() {
3256 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003257 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3258 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3259 String exclList = Settings.Global.getString(res,
3260 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003261 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3262 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003263 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003264 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003265 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003266 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003267 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003268 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003269 if (!proxyProperties.isValid()) {
3270 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3271 return;
3272 }
3273
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003274 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003275 mGlobalProxy = proxyProperties;
3276 }
3277 }
3278 }
3279
Jason Monk207900c2014-04-25 15:00:09 -04003280 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003281 // this information is already available as a world read/writable jvm property
3282 // so this API change wouldn't have a benifit. It also breaks the passing
3283 // of proxy info to all the JVMs.
3284 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003285 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003286 return mGlobalProxy;
3287 }
3288 }
3289
Jason Monk207900c2014-04-25 15:00:09 -04003290 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003291 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003292 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003293 proxy = null;
3294 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003295 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003296 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003297 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003298 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003299 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3300 return;
3301 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003302
3303 // This call could be coming from the PacManager, containing the port of the local
3304 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3305 // global (to get the correct local port), and send a broadcast.
3306 // TODO: Switch PacManager to have its own message to send back rather than
3307 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003308 if ((mGlobalProxy != null) && (proxy != null)
3309 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003310 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3311 mGlobalProxy = proxy;
3312 sendProxyBroadcast(mGlobalProxy);
3313 return;
3314 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003315 mDefaultProxy = proxy;
3316
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003317 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003318 if (!mDefaultProxyDisabled) {
3319 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003320 }
3321 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003322 }
3323
Paul Jensene0bef712014-12-10 15:12:18 -05003324 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3325 // This method gets called when any network changes proxy, but the broadcast only ever contains
3326 // the default proxy (even if it hasn't changed).
3327 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3328 // world where an app might be bound to a non-default network.
3329 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3330 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3331 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3332
3333 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3334 sendProxyBroadcast(getDefaultProxy());
3335 }
3336 }
3337
Robert Greenwalt434203a2010-10-11 16:00:27 -07003338 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003339 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3340 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 if (!TextUtils.isEmpty(proxy)) {
3342 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003343 if (data.length == 0) {
3344 return;
3345 }
3346
Robert Greenwalt434203a2010-10-11 16:00:27 -07003347 String proxyHost = data[0];
3348 int proxyPort = 8080;
3349 if (data.length > 1) {
3350 try {
3351 proxyPort = Integer.parseInt(data[1]);
3352 } catch (NumberFormatException e) {
3353 return;
3354 }
3355 }
Jason Monk207900c2014-04-25 15:00:09 -04003356 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 setGlobalProxy(p);
3358 }
3359 }
3360
Jason Monk207900c2014-04-25 15:00:09 -04003361 private void sendProxyBroadcast(ProxyInfo proxy) {
3362 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003363 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003364 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003365 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003366 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3367 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003368 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003369 final long ident = Binder.clearCallingIdentity();
3370 try {
3371 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3372 } finally {
3373 Binder.restoreCallingIdentity(ident);
3374 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 }
3376
3377 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003378 final private HashMap<Uri, Integer> mUriEventMap;
3379 final private Context mContext;
3380 final private Handler mHandler;
3381
3382 SettingsObserver(Context context, Handler handler) {
3383 super(null);
3384 mUriEventMap = new HashMap<Uri, Integer>();
3385 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003386 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003387 }
3388
Erik Klineda4bfa82015-04-30 12:58:40 +09003389 void observe(Uri uri, int what) {
3390 mUriEventMap.put(uri, what);
3391 final ContentResolver resolver = mContext.getContentResolver();
3392 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003393 }
3394
3395 @Override
3396 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003397 Slog.wtf(TAG, "Should never be reached.");
3398 }
3399
3400 @Override
3401 public void onChange(boolean selfChange, Uri uri) {
3402 final Integer what = mUriEventMap.get(uri);
3403 if (what != null) {
3404 mHandler.obtainMessage(what.intValue()).sendToTarget();
3405 } else {
3406 loge("No matching event to send for URI=" + uri);
3407 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 }
3409 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003410
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003411 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003412 Slog.d(TAG, s);
3413 }
3414
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003415 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003416 Slog.e(TAG, s);
3417 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003418
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003419 private static <T> T checkNotNull(T value, String message) {
3420 if (value == null) {
3421 throw new NullPointerException(message);
3422 }
3423 return value;
3424 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003425
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003426 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003427 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003428 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3429 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3430 *
3431 * @param oldPackage Package name of the application which currently controls VPN, which will
3432 * be replaced. If there is no such application, this should should either be
3433 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3434 * @param newPackage Package name of the application which should gain control of VPN, or
3435 * {@code null} to disable.
3436 * @param userId User for whom to prepare the new VPN.
3437 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003438 * @hide
3439 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003440 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003441 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3442 int userId) {
3443 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003444 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003445
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003446 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003447 Vpn vpn = mVpns.get(userId);
3448 if (vpn != null) {
3449 return vpn.prepare(oldPackage, newPackage);
3450 } else {
3451 return false;
3452 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003453 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003454 }
3455
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003456 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003457 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3458 * This method is used by system-privileged apps.
3459 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3460 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3461 *
3462 * @param packageName The package for which authorization state should change.
3463 * @param userId User for whom {@code packageName} is installed.
3464 * @param authorized {@code true} if this app should be able to start a VPN connection without
3465 * explicit user approval, {@code false} if not.
3466 *
Jeff Davidson05542602014-08-11 14:07:27 -07003467 * @hide
3468 */
3469 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003470 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3471 enforceCrossUserPermission(userId);
3472
Jeff Davidson05542602014-08-11 14:07:27 -07003473 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003474 Vpn vpn = mVpns.get(userId);
3475 if (vpn != null) {
3476 vpn.setPackageAuthorization(packageName, authorized);
3477 }
Jeff Davidson05542602014-08-11 14:07:27 -07003478 }
3479 }
3480
3481 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003482 * Configure a TUN interface and return its file descriptor. Parameters
3483 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003484 * and not available in ConnectivityManager. Permissions are checked in
3485 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003486 * @hide
3487 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003488 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003489 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003490 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003491 int user = UserHandle.getUserId(Binder.getCallingUid());
3492 synchronized(mVpns) {
3493 return mVpns.get(user).establish(config);
3494 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003495 }
3496
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003497 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003498 * Start legacy VPN, controlling native daemons as needed. Creates a
3499 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003500 */
3501 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003502 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003503 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003504 final LinkProperties egress = getActiveLinkProperties();
3505 if (egress == null) {
3506 throw new IllegalStateException("Missing active network connection");
3507 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 int user = UserHandle.getUserId(Binder.getCallingUid());
3509 synchronized(mVpns) {
3510 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3511 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003512 }
3513
3514 /**
3515 * Return the information of the ongoing legacy VPN. This method is used
3516 * by VpnSettings and not available in ConnectivityManager. Permissions
3517 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003518 */
3519 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003520 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3521 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003522
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003523 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003524 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003526 }
3527
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003528 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003529 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3530 * and not available in ConnectivityManager.
3531 */
3532 @Override
3533 public VpnInfo[] getAllVpnInfo() {
3534 enforceConnectivityInternalPermission();
3535 if (mLockdownEnabled) {
3536 return new VpnInfo[0];
3537 }
3538
3539 synchronized(mVpns) {
3540 List<VpnInfo> infoList = new ArrayList<>();
3541 for (int i = 0; i < mVpns.size(); i++) {
3542 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3543 if (info != null) {
3544 infoList.add(info);
3545 }
3546 }
3547 return infoList.toArray(new VpnInfo[infoList.size()]);
3548 }
3549 }
3550
3551 /**
3552 * @return VPN information for accounting, or null if we can't retrieve all required
3553 * information, e.g primary underlying iface.
3554 */
3555 @Nullable
3556 private VpnInfo createVpnInfo(Vpn vpn) {
3557 VpnInfo info = vpn.getVpnInfo();
3558 if (info == null) {
3559 return null;
3560 }
3561 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3562 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3563 // the underlyingNetworks list.
3564 if (underlyingNetworks == null) {
3565 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3566 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3567 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3568 }
3569 } else if (underlyingNetworks.length > 0) {
3570 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3571 if (linkProperties != null) {
3572 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3573 }
3574 }
3575 return info.primaryUnderlyingIface == null ? null : info;
3576 }
3577
3578 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003579 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3580 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003581 * Permissions are checked in Vpn class.
3582 * @hide
3583 */
3584 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003585 public VpnConfig getVpnConfig(int userId) {
3586 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003587 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003588 Vpn vpn = mVpns.get(userId);
3589 if (vpn != null) {
3590 return vpn.getVpnConfig();
3591 } else {
3592 return null;
3593 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003594 }
3595 }
3596
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003597 @Override
3598 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003599 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3600 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3601 return false;
3602 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003603
3604 // Tear down existing lockdown if profile was removed
3605 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3606 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003607 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3608 if (profileTag == null) {
3609 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3610 return false;
3611 }
3612 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003613 final VpnProfile profile = VpnProfile.decode(
3614 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003615 if (profile == null) {
3616 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3617 setLockdownTracker(null);
3618 return true;
3619 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003620 int user = UserHandle.getUserId(Binder.getCallingUid());
3621 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003622 Vpn vpn = mVpns.get(user);
3623 if (vpn == null) {
3624 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3625 return false;
3626 }
3627 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003628 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003629 } else {
3630 setLockdownTracker(null);
3631 }
3632
3633 return true;
3634 }
3635
3636 /**
3637 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3638 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3639 */
3640 private void setLockdownTracker(LockdownVpnTracker tracker) {
3641 // Shutdown any existing tracker
3642 final LockdownVpnTracker existing = mLockdownTracker;
3643 mLockdownTracker = null;
3644 if (existing != null) {
3645 existing.shutdown();
3646 }
3647
3648 try {
3649 if (tracker != null) {
3650 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003651 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003652 mLockdownTracker = tracker;
3653 mLockdownTracker.init();
3654 } else {
3655 mNetd.setFirewallEnabled(false);
3656 }
3657 } catch (RemoteException e) {
3658 // ignored; NMS lives inside system_server
3659 }
3660 }
3661
3662 private void throwIfLockdownEnabled() {
3663 if (mLockdownEnabled) {
3664 throw new IllegalStateException("Unavailable in lockdown mode");
3665 }
3666 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003667
Robin Lee244ce8e2016-01-05 18:03:46 +00003668 /**
Robin Lee17e61832016-05-09 13:46:28 +01003669 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3670 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003671 *
Robin Lee17e61832016-05-09 13:46:28 +01003672 * @return {@code true} if the service was started, the service was already connected, or there
3673 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003674 */
Robin Lee17e61832016-05-09 13:46:28 +01003675 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003676 synchronized (mVpns) {
3677 Vpn vpn = mVpns.get(userId);
3678 if (vpn == null) {
3679 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3680 // exists already.
3681 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3682 return false;
3683 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003684
Robin Lee812800c2016-05-13 15:38:08 +01003685 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003686 }
3687 }
3688
3689 @Override
Robin Leedc679712016-05-03 13:23:03 +01003690 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003691 enforceConnectivityInternalPermission();
3692 enforceCrossUserPermission(userId);
3693
3694 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3695 if (LockdownVpnTracker.isEnabled()) {
3696 return false;
3697 }
3698
Robin Lee244ce8e2016-01-05 18:03:46 +00003699 synchronized (mVpns) {
3700 Vpn vpn = mVpns.get(userId);
3701 if (vpn == null) {
3702 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3703 return false;
3704 }
Robin Lee17e61832016-05-09 13:46:28 +01003705 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003706 return false;
3707 }
Robin Lee17e61832016-05-09 13:46:28 +01003708 if (!startAlwaysOnVpn(userId)) {
3709 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003710 return false;
3711 }
Robin Lee17e61832016-05-09 13:46:28 +01003712
Robin Lee812800c2016-05-13 15:38:08 +01003713 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003714 }
3715 return true;
3716 }
3717
3718 @Override
3719 public String getAlwaysOnVpnPackage(int userId) {
3720 enforceConnectivityInternalPermission();
3721 enforceCrossUserPermission(userId);
3722
3723 synchronized (mVpns) {
3724 Vpn vpn = mVpns.get(userId);
3725 if (vpn == null) {
3726 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3727 return null;
3728 }
3729 return vpn.getAlwaysOnPackage();
3730 }
3731 }
3732
Wink Savilleab9321d2013-06-29 21:10:57 -07003733 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003734 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003735 // TODO: Remove? Any reason to trigger a provisioning check?
3736 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003737 }
3738
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003739 /** Location to an updatable file listing carrier provisioning urls.
3740 * An example:
3741 *
3742 * <?xml version="1.0" encoding="utf-8"?>
3743 * <provisioningUrls>
3744 * <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 -07003745 * </provisioningUrls>
3746 */
3747 private static final String PROVISIONING_URL_PATH =
3748 "/data/misc/radio/provisioning_urls.xml";
3749 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003750
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003751 /** XML tag for root element. */
3752 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3753 /** XML tag for individual url */
3754 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003755 /** XML attribute for mcc */
3756 private static final String ATTR_MCC = "mcc";
3757 /** XML attribute for mnc */
3758 private static final String ATTR_MNC = "mnc";
3759
Paul Jensen434dde82015-06-11 09:43:30 -04003760 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003761 FileReader fileReader = null;
3762 XmlPullParser parser = null;
3763 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003764
3765 try {
3766 fileReader = new FileReader(mProvisioningUrlFile);
3767 parser = Xml.newPullParser();
3768 parser.setInput(fileReader);
3769 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3770
3771 while (true) {
3772 XmlUtils.nextElement(parser);
3773
3774 String element = parser.getName();
3775 if (element == null) break;
3776
Paul Jensen434dde82015-06-11 09:43:30 -04003777 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003778 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3779 try {
3780 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3781 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3782 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3783 parser.next();
3784 if (parser.getEventType() == XmlPullParser.TEXT) {
3785 return parser.getText();
3786 }
3787 }
3788 }
3789 } catch (NumberFormatException e) {
3790 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3791 }
3792 }
3793 }
3794 return null;
3795 } catch (FileNotFoundException e) {
3796 loge("Carrier Provisioning Urls file not found");
3797 } catch (XmlPullParserException e) {
3798 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3799 } catch (IOException e) {
3800 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3801 } finally {
3802 if (fileReader != null) {
3803 try {
3804 fileReader.close();
3805 } catch (IOException e) {}
3806 }
3807 }
3808 return null;
3809 }
3810
Wink Saville42d4f082013-07-20 20:31:59 -07003811 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003812 public String getMobileProvisioningUrl() {
3813 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003814 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003815 if (TextUtils.isEmpty(url)) {
3816 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003817 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003818 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003819 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003820 }
Wink Saville8cf35602013-07-10 23:00:07 -07003821 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003822 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003823 String phoneNumber = mTelephonyManager.getLine1Number();
3824 if (TextUtils.isEmpty(phoneNumber)) {
3825 phoneNumber = "0000000000";
3826 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003827 url = String.format(url,
3828 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3829 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003830 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003831 }
3832
Wink Savilleab9321d2013-06-29 21:10:57 -07003833 return url;
3834 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003835
Wink Saville948282b2013-08-29 08:55:16 -07003836 @Override
3837 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003838 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003839 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003840 final long ident = Binder.clearCallingIdentity();
3841 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003842 // Concatenate the range of types onto the range of NetIDs.
3843 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3844 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003845 } finally {
3846 Binder.restoreCallingIdentity(ident);
3847 }
Wink Saville948282b2013-08-29 08:55:16 -07003848 }
Wink Saville7788c612013-08-29 14:57:08 -07003849
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003850 @Override
3851 public void setAirplaneMode(boolean enable) {
3852 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003853 final long ident = Binder.clearCallingIdentity();
3854 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003855 final ContentResolver cr = mContext.getContentResolver();
3856 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3857 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3858 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003859 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003860 } finally {
3861 Binder.restoreCallingIdentity(ident);
3862 }
3863 }
3864
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003865 private void onUserStart(int userId) {
3866 synchronized(mVpns) {
3867 Vpn userVpn = mVpns.get(userId);
3868 if (userVpn != null) {
3869 loge("Starting user already has a VPN");
3870 return;
3871 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003872 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003873 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003874
3875 final ContentResolver cr = mContext.getContentResolver();
3876 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3877 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3878 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3879 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3880 if (alwaysOnPackage != null) {
3881 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3882 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003883 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003884 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3885 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003886 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887 }
3888
3889 private void onUserStop(int userId) {
3890 synchronized(mVpns) {
3891 Vpn userVpn = mVpns.get(userId);
3892 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003893 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003894 return;
3895 }
Robin Lee17e61832016-05-09 13:46:28 +01003896 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003897 mVpns.delete(userId);
3898 }
3899 }
3900
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003901 private void onUserAdded(int userId) {
3902 synchronized(mVpns) {
3903 final int vpnsSize = mVpns.size();
3904 for (int i = 0; i < vpnsSize; i++) {
3905 Vpn vpn = mVpns.valueAt(i);
3906 vpn.onUserAdded(userId);
3907 }
3908 }
3909 }
3910
3911 private void onUserRemoved(int userId) {
3912 synchronized(mVpns) {
3913 final int vpnsSize = mVpns.size();
3914 for (int i = 0; i < vpnsSize; i++) {
3915 Vpn vpn = mVpns.valueAt(i);
3916 vpn.onUserRemoved(userId);
3917 }
3918 }
3919 }
3920
Robin Lee89e7a692016-02-29 14:38:17 +00003921 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003922 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3923 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3924 updateLockdownVpn();
3925 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003926 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003927 }
3928 }
3929
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003930 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3931 @Override
3932 public void onReceive(Context context, Intent intent) {
3933 final String action = intent.getAction();
3934 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3935 if (userId == UserHandle.USER_NULL) return;
3936
Robin Lee323f29d2016-05-04 16:38:06 +01003937 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003938 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003939 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003940 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003941 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3942 onUserAdded(userId);
3943 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3944 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003945 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3946 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003947 }
3948 }
3949 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003950
Robin Lee95204e02017-01-27 11:59:22 +00003951 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3952 @Override
3953 public void onReceive(Context context, Intent intent) {
3954 // Try creating lockdown tracker, since user present usually means
3955 // unlocked keystore.
3956 updateLockdownVpn();
3957 mContext.unregisterReceiver(this);
3958 }
3959 };
3960
Robert Greenwalta67be032014-05-16 15:49:14 -07003961 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3962 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3964 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003965
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003966 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3967 // Map from UID to number of NetworkRequests that UID has filed.
3968 @GuardedBy("mUidToNetworkRequestCount")
3969 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3970
Robert Greenwalta67be032014-05-16 15:49:14 -07003971 private static class NetworkFactoryInfo {
3972 public final String name;
3973 public final Messenger messenger;
3974 public final AsyncChannel asyncChannel;
3975
3976 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3977 this.name = name;
3978 this.messenger = messenger;
3979 this.asyncChannel = asyncChannel;
3980 }
3981 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003982
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003983 private void ensureNetworkRequestHasType(NetworkRequest request) {
3984 if (request.type == NetworkRequest.Type.NONE) {
3985 throw new IllegalArgumentException(
3986 "All NetworkRequests in ConnectivityService must have a type");
3987 }
3988 }
3989
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003990 /**
3991 * Tracks info about the requester.
3992 * Also used to notice when the calling process dies so we can self-expire
3993 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003995 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003996 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003997 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003998 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 final int mPid;
4000 final int mUid;
4001 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004002
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004003 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004004 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004005 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004006 mPendingIntent = pi;
4007 messenger = null;
4008 mBinder = null;
4009 mPid = getCallingPid();
4010 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004011 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 }
4013
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004014 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004015 super();
4016 messenger = m;
4017 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004018 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 mBinder = binder;
4020 mPid = getCallingPid();
4021 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004022 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004023 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024
4025 try {
4026 mBinder.linkToDeath(this, 0);
4027 } catch (RemoteException e) {
4028 binderDied();
4029 }
4030 }
4031
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004032 private void enforceRequestCountLimit() {
4033 synchronized (mUidToNetworkRequestCount) {
4034 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4035 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4036 throw new IllegalArgumentException("Too many NetworkRequests filed");
4037 }
4038 mUidToNetworkRequestCount.put(mUid, networkRequests);
4039 }
4040 }
4041
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004043 if (mBinder != null) {
4044 mBinder.unlinkToDeath(this, 0);
4045 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004046 }
4047
4048 public void binderDied() {
4049 log("ConnectivityService NetworkRequestInfo binderDied(" +
4050 request + ", " + mBinder + ")");
4051 releaseNetworkRequest(request);
4052 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004053
4054 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004055 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004056 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004057 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 }
4059
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004060 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4061 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4062 if (badCapability != null) {
4063 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004064 }
4065 }
4066
Erik Kline9d598e12015-07-13 16:37:51 +09004067 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004068 final SortedSet<Integer> thresholds = new TreeSet();
4069 synchronized (nai) {
4070 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4071 if (nri.request.networkCapabilities.hasSignalStrength() &&
4072 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4073 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4074 }
4075 }
4076 }
Erik Kline9d598e12015-07-13 16:37:51 +09004077 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004078 }
4079
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004080 private void updateSignalStrengthThresholds(
4081 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4082 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004083 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004084 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4085
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004086 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004087 String detail;
4088 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4089 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4090 } else {
4091 detail = reason;
4092 }
4093 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4094 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4095 }
4096
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004097 nai.asyncChannel.sendMessage(
4098 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004099 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004100 }
4101
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 @Override
4103 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004104 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004105 final NetworkRequest.Type type = (networkCapabilities == null)
4106 ? NetworkRequest.Type.TRACK_DEFAULT
4107 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004108 // If the requested networkCapabilities is null, take them instead from
4109 // the default network request. This allows callers to keep track of
4110 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004111 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004112 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4113 enforceAccessPermission();
4114 } else {
4115 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4116 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004117 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4118 // of the app when the request is filed, but we never change the request if the app
4119 // changes network state. http://b/29964605
4120 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004121 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004122 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004123
Etan Cohenba07c8c2017-02-05 10:42:27 -08004124 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004125 throw new IllegalArgumentException("Bad timeout specified");
4126 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004127
Etan Cohenddb9ef02015-11-18 10:56:15 -08004128 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4129 .equals(networkCapabilities.getNetworkSpecifier())) {
4130 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4131 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4132 }
4133
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004134 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004135 nextNetworkRequestId(), type);
4136 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004137 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004138
4139 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004140 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004142 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 }
4144 return networkRequest;
4145 }
4146
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004147 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004148 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004149 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004150 } else {
4151 enforceChangePermission();
4152 }
4153 }
4154
fenglub15e72b2015-03-20 11:29:56 -07004155 @Override
fengludb571472015-04-21 17:12:05 -07004156 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004157 enforceAccessPermission();
4158 NetworkAgentInfo nai = null;
4159 if (network == null) {
4160 return false;
4161 }
4162 synchronized (mNetworkForNetId) {
4163 nai = mNetworkForNetId.get(network.netId);
4164 }
4165 if (nai != null) {
4166 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4167 return true;
4168 }
4169 return false;
4170 }
4171
Felipe Lemeee27cab2016-06-20 16:36:29 -07004172 private boolean isSystem(int uid) {
4173 return uid < Process.FIRST_APPLICATION_UID;
4174 }
fenglub15e72b2015-03-20 11:29:56 -07004175
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004176 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004177 final int uid = Binder.getCallingUid();
4178 if (isSystem(uid)) {
4179 return;
4180 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004181 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004182 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004183 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004184 synchronized(mRulesLock) {
4185 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4186 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004187 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4188 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004189 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004190 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004191 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004192 }
4193 }
4194 }
4195
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196 @Override
4197 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4198 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004199 checkNotNull(operation, "PendingIntent cannot be null.");
4200 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4201 enforceNetworkRequestPermissions(networkCapabilities);
4202 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004203 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204
4205 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004206 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4207 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004208 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4210 nri));
4211 return networkRequest;
4212 }
4213
Jeremy Joslin79294842014-12-03 17:15:28 -08004214 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4215 mHandler.sendMessageDelayed(
4216 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4217 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4218 }
4219
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 @Override
4221 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004222 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004223 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4224 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 }
4226
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004227 // In order to implement the compatibility measure for pre-M apps that call
4228 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4229 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4230 // This ensures it has permission to do so.
4231 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4232 if (nc == null) {
4233 return false;
4234 }
4235 int[] transportTypes = nc.getTransportTypes();
4236 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4237 return false;
4238 }
4239 try {
4240 mContext.enforceCallingOrSelfPermission(
4241 android.Manifest.permission.ACCESS_WIFI_STATE,
4242 "ConnectivityService");
4243 } catch (SecurityException e) {
4244 return false;
4245 }
4246 return true;
4247 }
4248
Robert Greenwalt9258c642014-03-26 16:47:06 -07004249 @Override
4250 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4251 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004252 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4253 enforceAccessPermission();
4254 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004256 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4257 if (!ConnectivityManager.checkChangePermission(mContext)) {
4258 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4259 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4260 // onLost and onAvailable callbacks when networks move in and out of the background.
4261 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4262 // can't request networks.
4263 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4264 }
4265
4266 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004267 NetworkRequest.Type.LISTEN);
4268 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004269 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270
4271 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4272 return networkRequest;
4273 }
4274
4275 @Override
4276 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4277 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004278 checkNotNull(operation, "PendingIntent cannot be null.");
4279 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4280 enforceAccessPermission();
4281 }
4282
Erik Kline7523eb32015-07-09 18:24:03 +09004283 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004284 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4285 NetworkRequest.Type.LISTEN);
4286 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004287 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004288
4289 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004290 }
4291
Erik Klineacdd6392016-07-07 16:50:58 +09004292 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004293 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004294 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004295 mHandler.sendMessage(mHandler.obtainMessage(
4296 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004297 }
4298
4299 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004300 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004301 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004302 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4303 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004304 }
4305
Robert Greenwalta67be032014-05-16 15:49:14 -07004306 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004307 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004308 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4309 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4310 }
4311
4312 @Override
4313 public void unregisterNetworkFactory(Messenger messenger) {
4314 enforceConnectivityInternalPermission();
4315 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4316 }
4317
4318 private void handleUnregisterNetworkFactory(Messenger messenger) {
4319 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4320 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004321 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004322 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004323 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004324 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004325 }
4326
Robert Greenwalt7b816022014-04-18 15:25:25 -07004327 /**
4328 * NetworkAgentInfo supporting a request by requestId.
4329 * These have already been vetted (their Capabilities satisfy the request)
4330 * and the are the highest scored network available.
4331 * the are keyed off the Requests requestId.
4332 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004333 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4335 new SparseArray<NetworkAgentInfo>();
4336
Paul Jensen31a94f42015-02-13 14:18:39 -05004337 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4338 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004339 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4340 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004341 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4342 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4343 // there may not be a strict 1:1 correlation between the two.
4344 @GuardedBy("mNetworkForNetId")
4345 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346
Robert Greenwalt7b816022014-04-18 15:25:25 -07004347 // NetworkAgentInfo keyed off its connecting messenger
4348 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004349 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4351 new HashMap<Messenger, NetworkAgentInfo>();
4352
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004353 @GuardedBy("mBlockedAppUids")
4354 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4355
Paul Jensen2c311d62014-11-17 12:34:51 -05004356 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004357 private final NetworkRequest mDefaultRequest;
4358
Erik Klineda4bfa82015-04-30 12:58:40 +09004359 // Request used to optionally keep mobile data active even when higher
4360 // priority networks like Wi-Fi are active.
4361 private final NetworkRequest mDefaultMobileDataRequest;
4362
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004363 private NetworkAgentInfo getDefaultNetwork() {
4364 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4365 }
4366
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004367 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004368 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004369 }
4370
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004371 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4372 return nri.request.requestId == mDefaultRequest.requestId;
4373 }
4374
Paul Jensen31a94f42015-02-13 14:18:39 -05004375 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004376 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004377 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 enforceConnectivityInternalPermission();
4379
Paul Jensen2c311d62014-11-17 12:34:51 -05004380 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4381 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004382 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004383 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4384 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004385 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004386 synchronized (this) {
4387 nai.networkMonitor.systemReady = mSystemReady;
4388 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004389 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4390 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004391 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004393 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 }
4395
4396 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4397 if (VDBG) log("Got NetworkAgent Messenger");
4398 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004399 synchronized (mNetworkForNetId) {
4400 mNetworkForNetId.put(na.network.netId, na);
4401 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4403 NetworkInfo networkInfo = na.networkInfo;
4404 na.networkInfo = null;
4405 updateNetworkInfo(na, networkInfo);
4406 }
4407
4408 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4409 LinkProperties newLp = networkAgent.linkProperties;
4410 int netId = networkAgent.network.netId;
4411
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004412 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4413 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004414 if (networkAgent.clatd != null) {
4415 networkAgent.clatd.fixupLinkProperties(oldLp);
4416 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004417
Paul Jensen992f2522014-04-28 10:33:11 -04004418 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004419 updateMtu(newLp, oldLp);
4420 // TODO - figure out what to do for clat
4421// for (LinkProperties lp : newLp.getStackedLinks()) {
4422// updateMtu(lp, null);
4423// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004424 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004425
Erik Kline94887872016-04-05 13:30:49 +09004426 updateRoutes(newLp, oldLp, netId);
4427 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004428
Paul Jensen3b759822014-05-13 11:44:01 -04004429 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004430 if (isDefaultNetwork(networkAgent)) {
4431 handleApplyDefaultProxy(newLp.getHttpProxy());
4432 } else {
4433 updateProxy(newLp, oldLp, networkAgent);
4434 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004435 // TODO - move this check to cover the whole function
4436 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004437 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004438 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4439 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004440
4441 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004442 }
4443
Lorenzo Colitti95439462014-10-09 13:44:48 +09004444 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4445 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4446 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004447
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004448 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004449 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4450 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004451 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004452 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004453 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 }
Paul Jensen992f2522014-04-28 10:33:11 -04004455
4456 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4457 CompareResult<String> interfaceDiff = new CompareResult<String>();
4458 if (oldLp != null) {
4459 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4460 } else if (newLp != null) {
4461 interfaceDiff.added = newLp.getAllInterfaceNames();
4462 }
4463 for (String iface : interfaceDiff.added) {
4464 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004465 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004466 mNetd.addInterfaceToNetwork(iface, netId);
4467 } catch (Exception e) {
4468 loge("Exception adding interface: " + e);
4469 }
4470 }
4471 for (String iface : interfaceDiff.removed) {
4472 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004473 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004474 mNetd.removeInterfaceFromNetwork(iface, netId);
4475 } catch (Exception e) {
4476 loge("Exception removing interface: " + e);
4477 }
4478 }
4479 }
4480
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004481 /**
4482 * Have netd update routes from oldLp to newLp.
4483 * @return true if routes changed between oldLp and newLp
4484 */
4485 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004486 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4487 if (oldLp != null) {
4488 routeDiff = oldLp.compareAllRoutes(newLp);
4489 } else if (newLp != null) {
4490 routeDiff.added = newLp.getAllRoutes();
4491 }
4492
4493 // add routes before removing old in case it helps with continuous connectivity
4494
4495 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4496 for (RouteInfo route : routeDiff.added) {
4497 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004498 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 try {
4500 mNetd.addRoute(netId, route);
4501 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004502 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4503 loge("Exception in addRoute for non-gateway: " + e);
4504 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004505 }
4506 }
4507 for (RouteInfo route : routeDiff.added) {
4508 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004509 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 try {
4511 mNetd.addRoute(netId, route);
4512 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004513 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4514 loge("Exception in addRoute for gateway: " + e);
4515 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 }
4517 }
4518
4519 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004520 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 try {
4522 mNetd.removeRoute(netId, route);
4523 } catch (Exception e) {
4524 loge("Exception in removeRoute: " + e);
4525 }
4526 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004527 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528 }
Erik Kline41368502015-06-17 13:19:54 +09004529
Erik Kline94887872016-04-05 13:30:49 +09004530 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4531 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4532 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 }
Erik Kline94887872016-04-05 13:30:49 +09004534
4535 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004536 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004537 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004538 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004539 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4540 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004541 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004542 }
Erik Kline94887872016-04-05 13:30:49 +09004543 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 }
4545
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004546 private String getNetworkPermission(NetworkCapabilities nc) {
4547 // TODO: make these permission strings AIDL constants instead.
4548 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4549 return NetworkManagementService.PERMISSION_SYSTEM;
4550 }
4551 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4552 return NetworkManagementService.PERMISSION_NETWORK;
4553 }
4554 return null;
4555 }
4556
Paul Jensen3d194ea2015-06-16 14:27:36 -04004557 /**
4558 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4559 * augmented with any stateful capabilities implied from {@code networkAgent}
4560 * (e.g., validated status and captive portal status).
4561 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004562 * @param oldScore score of the network before any of the changes that prompted us
4563 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004564 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004565 * @param networkCapabilities the new network capabilities.
4566 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004567 private void updateCapabilities(
4568 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004569 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4570 networkCapabilities)) {
4571 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4572 + nai.networkCapabilities + " -> " + networkCapabilities);
4573 }
4574
Paul Jensen3d194ea2015-06-16 14:27:36 -04004575 // Don't modify caller's NetworkCapabilities.
4576 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004577 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004578 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4579 } else {
4580 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4581 }
Paul Jensene0988542015-06-25 15:30:08 -04004582 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004583 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4584 } else {
4585 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4586 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004587 if (nai.isBackgroundNetwork()) {
4588 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4589 } else {
4590 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4591 }
4592
4593 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4594
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004595 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4596 final String newPermission = getNetworkPermission(networkCapabilities);
4597 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004598 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004599 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004600 } catch (RemoteException e) {
4601 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004602 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004603 }
4604
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004605 final NetworkCapabilities prevNc = nai.networkCapabilities;
4606 synchronized (nai) {
4607 nai.networkCapabilities = networkCapabilities;
4608 }
4609 if (nai.getCurrentScore() == oldScore &&
4610 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4611 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4612 // the change we're processing can't affect any requests, it can only affect the listens
4613 // on this network. We might have been called by rematchNetworkAndRequests when a
4614 // network changed foreground state.
4615 processListenRequests(nai, true);
4616 } else {
4617 // If the requestable capabilities have changed or the score changed, we can't have been
4618 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004619 rematchAllNetworksAndRequests(nai, oldScore);
4620 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004621 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004622 }
4623
Paul Jensenc8b9a742014-09-30 15:37:41 -04004624 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004625 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4626 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004627 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004628 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004629 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4630 }
4631 }
4632
Robert Greenwalt7b816022014-04-18 15:25:25 -07004633 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4634 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004635 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004636 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4637 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004638 }
4639 }
4640
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004641 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4642 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004643 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004644 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4646 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004647 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004648 sendIntent(nri.mPendingIntent, intent);
4649 }
4650 // else not handled
4651 }
4652
4653 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4654 mPendingIntentWakeLock.acquire();
4655 try {
4656 if (DBG) log("Sending " + pendingIntent);
4657 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4658 } catch (PendingIntent.CanceledException e) {
4659 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4660 mPendingIntentWakeLock.release();
4661 releasePendingNetworkRequest(pendingIntent);
4662 }
4663 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4664 }
4665
4666 @Override
4667 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4668 String resultData, Bundle resultExtras) {
4669 if (DBG) log("Finished sending " + pendingIntent);
4670 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004671 // Release with a delay so the receiving client has an opportunity to put in its
4672 // own request.
4673 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004674 }
4675
Robert Greenwalt9258c642014-03-26 16:47:06 -07004676 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004677 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004678 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004679 Bundle bundle = new Bundle();
4680 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4681 new NetworkRequest(nri.request));
4682 Message msg = Message.obtain();
4683 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4684 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4685 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4686 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004687 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004688 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004689 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004690 break;
4691 }
4692 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4693 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4694 new NetworkCapabilities(networkAgent.networkCapabilities));
4695 break;
4696 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004697 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004698 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4699 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004700 break;
4701 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004702 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004703 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004704 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004705 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004706 if (VDBG) {
4707 log("sending notification " + notifyTypeToName(notificationType) +
4708 " for " + nri.request);
4709 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004710 nri.messenger.send(msg);
4711 } catch (RemoteException e) {
4712 // may occur naturally in the race of binder death.
4713 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4714 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004715 }
4716
Paul Jensenc8b9a742014-09-30 15:37:41 -04004717 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004718 if (nai.numRequestNetworkRequests() != 0) {
4719 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4720 NetworkRequest nr = nai.requestAt(i);
4721 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004722 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004723 loge("Dead network still had at least " + nr);
4724 break;
4725 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004726 }
4727 nai.asyncChannel.disconnect();
4728 }
4729
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4731 if (oldNetwork == null) {
4732 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4733 return;
4734 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004735 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004736
4737 // If we get here it means that the last linger timeout for this network expired. So there
4738 // must be no other active linger timers, and we must stop lingering.
4739 oldNetwork.clearLingerState();
4740
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004741 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004742 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004743 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004744 } else {
4745 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004746 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4747 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004749 }
4750
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004751 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004752 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004753 setupDataActivityTracking(newNetwork);
4754 try {
4755 mNetd.setDefaultNetId(newNetwork.network.netId);
4756 } catch (Exception e) {
4757 loge("Exception setting default network :" + e);
4758 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004759 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004760 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004761 updateTcpBufferSizes(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004762 }
4763
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004764 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004765 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4766 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4767 NetworkRequest nr = nri.request;
4768 if (!nr.isListen()) continue;
4769 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4770 nai.removeRequest(nri.request.requestId);
4771 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4772 }
4773 }
4774
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004775 if (capabilitiesChanged) {
4776 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4777 }
4778
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004779 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4780 NetworkRequest nr = nri.request;
4781 if (!nr.isListen()) continue;
4782 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4783 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004784 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004785 }
4786 }
4787 }
4788
Paul Jensen2161a8e2014-09-11 11:00:39 -04004789 // Handles a network appearing or improving its score.
4790 //
4791 // - Evaluates all current NetworkRequests that can be
4792 // satisfied by newNetwork, and reassigns to newNetwork
4793 // any such requests for which newNetwork is the best.
4794 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004795 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004796 // needed. A network is needed if it is the best network for
4797 // one or more NetworkRequests, or if it is a VPN.
4798 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004799 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004800 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004801 //
4802 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4803 // networks that have no chance (i.e. even if validated)
4804 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004805 //
4806 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4807 // it does not remove NetworkRequests that other Networks could better satisfy.
4808 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4809 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4810 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004811 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004812 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004813 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4814 // performed to tear down unvalidated networks that have no chance (i.e. even if
4815 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004816 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004817 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004818 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004819 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004820 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004821 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004822
4823 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4824 final int score = newNetwork.getCurrentScore();
4825
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004826 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827
Paul Jensen2161a8e2014-09-11 11:00:39 -04004828 // Find and migrate to this Network any NetworkRequests for
4829 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004830 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004831 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004832 NetworkCapabilities nc = newNetwork.networkCapabilities;
4833 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004834 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004835 // Process requests in the first pass and listens in the second pass. This allows us to
4836 // change a network's capabilities depending on which requests it has. This is only
4837 // correct if the change in capabilities doesn't affect whether the network satisfies
4838 // requests or not, and doesn't affect the network's score.
4839 if (nri.request.isListen()) continue;
4840
Paul Jensencf4c2c62015-07-01 14:16:32 -04004841 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4842 final boolean satisfies = newNetwork.satisfies(nri.request);
4843 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004844 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004845 log("Network " + newNetwork.name() + " was already satisfying" +
4846 " request " + nri.request.requestId + ". No change.");
4847 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004848 keep = true;
4849 continue;
4850 }
4851
4852 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004853 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004854 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004855 // next check if it's better than any current network we're using for
4856 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004857 if (VDBG) {
4858 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004859 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004860 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004862 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004863 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004864 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004865 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004866 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004867 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004868 affectedNetworks.add(currentNetwork);
4869 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004870 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004871 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004872 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004873 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004874 if (!newNetwork.addRequest(nri.request)) {
4875 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4876 }
4877 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004878 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004879 // Tell NetworkFactories about the new score, so they can stop
4880 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004881 // TODO - this could get expensive if we have alot of requests for this
4882 // network. Think about if there is a way to reduce this. Push
4883 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004884 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004885 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004886 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004887 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004888 if (currentNetwork != null) {
4889 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4890 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891 }
4892 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004893 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004894 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4895 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004896 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004897 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4898 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4899 // This means this code doesn't have to handle the case where "currentNetwork" no
4900 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4901 if (DBG) {
4902 log("Network " + newNetwork.name() + " stopped satisfying" +
4903 " request " + nri.request.requestId);
4904 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004905 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004906 if (currentNetwork == newNetwork) {
4907 mNetworkForRequestId.remove(nri.request.requestId);
4908 sendUpdatedScoreToFactories(nri.request, 0);
4909 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004910 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4911 newNetwork.name() +
4912 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004913 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004914 // TODO: Technically, sending CALLBACK_LOST here is
4915 // incorrect if there is a replacement network currently
4916 // connected that can satisfy nri, which is a request
4917 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004918 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4919 // so this code is only incorrect for a network that loses
4920 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004921 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004922 }
4923 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004924 if (isNewDefault) {
4925 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004926 makeDefault(newNetwork);
4927 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4928 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004929 // Have a new default network, release the transition wakelock in
4930 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004931 }
4932
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004933 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4934 Slog.wtf(TAG, String.format(
4935 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4936 nc, newNetwork.networkCapabilities));
4937 }
4938 if (newNetwork.getCurrentScore() != score) {
4939 Slog.wtf(TAG, String.format(
4940 "BUG: %s changed score during rematch: %d -> %d",
4941 score, newNetwork.getCurrentScore()));
4942 }
4943
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004944 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004945 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4946 // If the network went from background to foreground or vice versa, we need to update
4947 // its foreground state. It is safe to do this after rematching the requests because
4948 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4949 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004950 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004951 } else {
4952 processListenRequests(newNetwork, false);
4953 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004954
Paul Jensencf4c2c62015-07-01 14:16:32 -04004955 // do this after the default net is switched, but
4956 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004957 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004958
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004959 // Linger any networks that are no longer needed. This should be done after sending the
4960 // available callback for newNetwork.
4961 for (NetworkAgentInfo nai : affectedNetworks) {
4962 updateLingerState(nai, now);
4963 }
4964 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4965 // does not need to be done in any particular order.
4966 updateLingerState(newNetwork, now);
4967
Paul Jensencf4c2c62015-07-01 14:16:32 -04004968 if (isNewDefault) {
4969 // Maintain the illusion: since the legacy API only
4970 // understands one network at a time, we must pretend
4971 // that the current default network disconnected before
4972 // the new one connected.
4973 if (oldDefaultNetwork != null) {
4974 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4975 oldDefaultNetwork, true);
4976 }
4977 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4978 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4979 notifyLockdownVpn(newNetwork);
4980 }
4981
Robert Greenwalt7b816022014-04-18 15:25:25 -07004982 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004983 // Notify battery stats service about this network, both the normal
4984 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004985 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004986 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004987 final IBatteryStats bs = BatteryStatsService.getService();
4988 final int type = newNetwork.networkInfo.getType();
4989
4990 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4991 bs.noteNetworkInterfaceType(baseIface, type);
4992 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4993 final String stackedIface = stacked.getInterfaceName();
4994 bs.noteNetworkInterfaceType(stackedIface, type);
4995 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4996 }
4997 } catch (RemoteException ignored) {
4998 }
4999
Robert Greenwalt152ed372014-12-17 17:19:53 -08005000 // This has to happen after the notifyNetworkCallbacks as that tickles each
5001 // ConnectivityManager instance so that legacy requests correctly bind dns
5002 // requests to this network. The legacy users are listening for this bcast
5003 // and will generally do a dns request so they can ensureRouteToHost and if
5004 // they do that before the callbacks happen they'll use the default network.
5005 //
5006 // TODO: Is there still a race here? We send the broadcast
5007 // after sending the callback, but if the app can receive the
5008 // broadcast before the callback, it might still break.
5009 //
5010 // This *does* introduce a race where if the user uses the new api
5011 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5012 // they may get old info. Reverse this after the old startUsing api is removed.
5013 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005014 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5015 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005016 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005017 // legacy type tracker filters out repeat adds
5018 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5019 }
5020 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005021
5022 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5023 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5024 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5025 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5026 if (newNetwork.isVPN()) {
5027 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005029 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005030 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5031 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005032 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005033 if (nai.getLingerExpiry() > 0) {
5034 // This network has active linger timers and no requests, but is not
5035 // lingering. Linger it.
5036 //
5037 // One way (the only way?) this can happen if this network is unvalidated
5038 // and became unneeded due to another network improving its score to the
5039 // point where this network will no longer be able to satisfy any requests
5040 // even if it validates.
5041 updateLingerState(nai, now);
5042 } else {
5043 if (DBG) log("Reaping " + nai.name());
5044 teardownUnneededNetwork(nai);
5045 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005046 }
5047 }
5048 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005049 }
5050
Paul Jensen1c7ba022015-06-16 14:27:36 -04005051 /**
5052 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5053 * being disconnected.
5054 * @param changed If only one Network's score or capabilities have been modified since the last
5055 * time this function was called, pass this Network in this argument, otherwise pass
5056 * null.
5057 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5058 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5059 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5060 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5061 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005062 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005063 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005064 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5065 // to avoid the slowness. It is not simply enough to process just "changed", for
5066 // example in the case where "changed"'s score decreases and another network should begin
5067 // satifying a NetworkRequest that "changed" currently satisfies.
5068
5069 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5070 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5071 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005072 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005073 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005074 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005075 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005076 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5077 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5078 // Rematch higher scoring networks first to prevent requests first matching a lower
5079 // scoring network and then a higher scoring network, which could produce multiple
5080 // callbacks and inadvertently unlinger networks.
5081 Arrays.sort(nais);
5082 for (NetworkAgentInfo nai : nais) {
5083 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005084 // Only reap the last time through the loop. Reaping before all rematching
5085 // is complete could incorrectly teardown a network that hasn't yet been
5086 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005087 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005088 : ReapUnvalidatedNetworks.REAP,
5089 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005090 }
5091 }
5092 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005094 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005095 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005096 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005097 // For now only update icons for default connection.
5098 // TODO: Update WiFi and cellular icons separately. b/17237507
5099 if (!isDefaultNetwork(nai)) return;
5100
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005101 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005102 // Don't repeat publish.
5103 if (newInetCondition == mDefaultInetConditionPublished) return;
5104
5105 mDefaultInetConditionPublished = newInetCondition;
5106 sendInetConditionBroadcast(nai.networkInfo);
5107 }
5108
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005109 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5110 if (mLockdownTracker != null) {
5111 if (nai != null && nai.isVPN()) {
5112 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5113 } else {
5114 mLockdownTracker.onNetworkInfoChanged();
5115 }
5116 }
5117 }
5118
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005120 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005121 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005122 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005123 synchronized (networkAgent) {
5124 oldInfo = networkAgent.networkInfo;
5125 networkAgent.networkInfo = newInfo;
5126 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005127 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005128
5129 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005130 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5131 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5132 notifyIfacesChangedForNetworkStats();
5133 } else if (VDBG) log("ignoring duplicate network state non-change");
5134 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005135 return;
5136 }
5137 if (DBG) {
5138 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5139 (oldInfo == null ? "null" : oldInfo.getState()) +
5140 " to " + state);
5141 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005142
Robin Lee585e2482016-05-01 23:00:00 +01005143 if (!networkAgent.created
5144 && (state == NetworkInfo.State.CONNECTED
5145 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005146
5147 // A network that has just connected has zero requests and is thus a foreground network.
5148 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5149
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005151 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005152 if (networkAgent.isVPN()) {
5153 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005154 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5155 (networkAgent.networkMisc == null ||
5156 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005157 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005158 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005159 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005160 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005161 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005162 loge("Error creating network " + networkAgent.network.netId + ": "
5163 + e.getMessage());
5164 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005165 }
Paul Jenseneec75412014-08-04 12:21:19 -04005166 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005167 }
5168
5169 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5170 networkAgent.everConnected = true;
5171
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005173 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005174
Paul Jensenca8f16a2014-05-09 12:47:55 -04005175 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005176 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005177
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005178 if (networkAgent.isVPN()) {
5179 // Temporarily disable the default proxy (not global).
5180 synchronized (mProxyLock) {
5181 if (!mDefaultProxyDisabled) {
5182 mDefaultProxyDisabled = true;
5183 if (mGlobalProxy == null && mDefaultProxy != null) {
5184 sendProxyBroadcast(null);
5185 }
5186 }
5187 }
5188 // TODO: support proxy per network.
5189 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005190
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005191 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5192 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5193 // capabilities, so it only needs to be done once on initial connect, not every time the
5194 // network's capabilities change. Note that we do this before rematching the network,
5195 // so we could decide to tear it down immediately afterwards. That's fine though - on
5196 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5197 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005198 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005199
Paul Jensen2161a8e2014-09-11 11:00:39 -04005200 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005201 final long now = SystemClock.elapsedRealtime();
5202 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005203
5204 // This has to happen after matching the requests, because callbacks are just requests.
5205 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005206 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005207 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005208 if (networkAgent.isVPN()) {
5209 synchronized (mProxyLock) {
5210 if (mDefaultProxyDisabled) {
5211 mDefaultProxyDisabled = false;
5212 if (mGlobalProxy == null && mDefaultProxy != null) {
5213 sendProxyBroadcast(mDefaultProxy);
5214 }
5215 }
5216 }
5217 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005218 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5219 state == NetworkInfo.State.SUSPENDED) {
5220 // going into or coming out of SUSPEND: rescore and notify
5221 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005222 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005223 }
5224 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5225 ConnectivityManager.CALLBACK_SUSPENDED :
5226 ConnectivityManager.CALLBACK_RESUMED));
5227 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005228 }
5229 }
5230
Robert Greenwaltac96c522014-06-03 16:43:57 -07005231 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005232 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005233 if (score < 0) {
5234 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5235 "). Bumping score to min of 0");
5236 score = 0;
5237 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005238
Paul Jensen2161a8e2014-09-11 11:00:39 -04005239 final int oldScore = nai.getCurrentScore();
5240 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005241
Paul Jensen85cf78e2015-06-25 13:25:07 -04005242 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005243
Paul Jensenc8b9a742014-09-30 15:37:41 -04005244 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005245 }
5246
Erik Klinec75d4fa2017-02-15 19:59:17 +09005247 // Notify only this one new request of the current state. Transfer all the
5248 // current state by calling NetworkCapabilities and LinkProperties callbacks
5249 // so that callers can be guaranteed to have as close to atomicity in state
5250 // transfer as can be supported by this current API.
5251 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005252 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005253 if (nri.mPendingIntent != null) {
5254 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5255 // Attempt no subsequent state pushes where intents are involved.
5256 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005257 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005258
5259 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5260 // Whether a network is currently suspended is also an important
5261 // element of state to be transferred (it would not otherwise be
5262 // delivered by any currently available mechanism).
5263 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5264 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5265 }
5266 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5267 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005268 }
5269
Robert Greenwalt8d482522015-06-24 13:23:42 -07005270 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005271 // The NetworkInfo we actually send out has no bearing on the real
5272 // state of affairs. For example, if the default connection is mobile,
5273 // and a request for HIPRI has just gone away, we need to pretend that
5274 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5275 // the state to DISCONNECTED, even though the network is of type MOBILE
5276 // and is still connected.
5277 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5278 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005279 if (state != DetailedState.DISCONNECTED) {
5280 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005281 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005282 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005283 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005284 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5285 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5286 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5287 if (info.isFailover()) {
5288 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5289 nai.networkInfo.setFailover(false);
5290 }
5291 if (info.getReason() != null) {
5292 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5293 }
5294 if (info.getExtraInfo() != null) {
5295 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5296 }
5297 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005298 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005299 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005300 if (newDefaultAgent != null) {
5301 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5302 newDefaultAgent.networkInfo);
5303 } else {
5304 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5305 }
5306 }
5307 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5308 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005309 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005310 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005311 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005312 }
5313 }
5314 }
5315
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005316 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005317 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005318 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5319 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005320 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5321 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005322 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5323 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005324 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005325 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005326 } else {
5327 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5328 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005329 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005330 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005331
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005332 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5333 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5334 }
5335
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005336 private String notifyTypeToName(int notifyType) {
5337 switch (notifyType) {
5338 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5339 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5340 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5341 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5342 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5343 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5344 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5345 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5346 }
5347 return "UNKNOWN";
5348 }
5349
Jeff Sharkey69736342014-12-08 14:50:12 -08005350 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005351 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5352 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005353 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005354 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005355 try {
5356 mStatsService.forceUpdateIfaces();
5357 } catch (Exception ignored) {
5358 }
5359 }
5360
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005361 @Override
5362 public boolean addVpnAddress(String address, int prefixLength) {
5363 throwIfLockdownEnabled();
5364 int user = UserHandle.getUserId(Binder.getCallingUid());
5365 synchronized (mVpns) {
5366 return mVpns.get(user).addAddress(address, prefixLength);
5367 }
5368 }
5369
5370 @Override
5371 public boolean removeVpnAddress(String address, int prefixLength) {
5372 throwIfLockdownEnabled();
5373 int user = UserHandle.getUserId(Binder.getCallingUid());
5374 synchronized (mVpns) {
5375 return mVpns.get(user).removeAddress(address, prefixLength);
5376 }
5377 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005378
5379 @Override
5380 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5381 throwIfLockdownEnabled();
5382 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005383 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005384 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005385 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005386 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005387 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005388 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005389 }
5390 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005391 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005392
5393 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005394 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005395 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005396 }
5397
5398 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005399 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5400 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5401 enforceKeepalivePermission();
5402 mKeepaliveTracker.startNattKeepalive(
5403 getNetworkAgentInfoForNetwork(network),
5404 intervalSeconds, messenger, binder,
5405 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5406 }
5407
5408 @Override
5409 public void stopKeepalive(Network network, int slot) {
5410 mHandler.sendMessage(mHandler.obtainMessage(
5411 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5412 }
5413
5414 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005415 public void factoryReset() {
5416 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005417
5418 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5419 return;
5420 }
5421
Robin Lee3b3dd942015-05-12 18:14:58 +01005422 final int userId = UserHandle.getCallingUserId();
5423
Stuart Scottf1fb3972015-04-02 18:00:02 -07005424 // Turn airplane mode off
5425 setAirplaneMode(false);
5426
Stuart Scotte3e314d2015-04-20 14:07:45 -07005427 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5428 // Untether
5429 for (String tether : getTetheredIfaces()) {
5430 untether(tether);
5431 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005432 }
5433
Stuart Scotte3e314d2015-04-20 14:07:45 -07005434 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005435 // Remove always-on package
5436 synchronized (mVpns) {
5437 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5438 if (alwaysOnPackage != null) {
5439 setAlwaysOnVpnPackage(userId, null, false);
5440 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5441 }
5442 }
5443
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005444 // Turn Always-on VPN off
5445 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5446 final long ident = Binder.clearCallingIdentity();
5447 try {
5448 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5449 mLockdownEnabled = false;
5450 setLockdownTracker(null);
5451 } finally {
5452 Binder.restoreCallingIdentity(ident);
5453 }
5454 }
5455
Stuart Scotte3e314d2015-04-20 14:07:45 -07005456 // Turn VPN off
5457 VpnConfig vpnConfig = getVpnConfig(userId);
5458 if (vpnConfig != null) {
5459 if (vpnConfig.legacy) {
5460 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5461 } else {
5462 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5463 // in the future without user intervention.
5464 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465
Victor Changb04a5ea2016-05-30 20:36:30 +01005466 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005467 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005468 }
5469 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005470
5471 Settings.Global.putString(mContext.getContentResolver(),
5472 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005473 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005474
5475 @VisibleForTesting
5476 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5477 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5478 return new NetworkMonitor(context, handler, nai, defaultRequest);
5479 }
Erik Kline48f12f22016-04-14 17:30:59 +09005480
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005481 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005482 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5483 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005484 }
5485
5486 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005487 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5488 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5489 }
5490
Hugo Benichicfddd682016-05-31 16:28:06 +09005491 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005492 int newNetid = NETID_UNSET;
5493 int prevNetid = NETID_UNSET;
5494 int[] transports = new int[0];
5495 boolean hadIPv4 = false;
5496 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005497
Hugo Benichi5f16f762016-04-20 12:09:33 +09005498 if (newNai != null) {
5499 newNetid = newNai.network.netId;
5500 transports = newNai.networkCapabilities.getTransportTypes();
5501 }
5502 if (prevNai != null) {
5503 prevNetid = prevNai.network.netId;
5504 final LinkProperties lp = prevNai.linkProperties;
5505 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5506 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5507 }
5508
Hugo Benichicfddd682016-05-31 16:28:06 +09005509 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5510 }
5511
5512 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5513 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515}