blob: d90703579ada097cebda5b989a9fff72f4bca3a5 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500114import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400120import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700122import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700124import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800125import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700126import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700127import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700128import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900129import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900130import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700131import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400133import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900134import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700135import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900136import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900137import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700138import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600139import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900141import com.android.server.connectivity.NetworkNotificationManager;
142import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400143import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700144import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800145import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700146import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700147import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700148import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600149
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700150import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700151
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import org.xmlpull.v1.XmlPullParser;
153import org.xmlpull.v1.XmlPullParserException;
154
155import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700157import java.io.FileNotFoundException;
158import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700159import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700161import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.net.InetAddress;
163import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700164import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700167import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700169import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700170import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700171import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700172import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600173import java.util.SortedSet;
174import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
176/**
177 * @hide
178 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800179public class ConnectivityService extends IConnectivityManager.Stub
180 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900181 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900183 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700184 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Jake Hamby786e71a2014-02-06 14:43:50 -0800186 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900187 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188
Jeff Sharkey899223b2012-08-04 15:24:58 -0700189 // TODO: create better separation between radio types and network types
190
Robert Greenwalt42acef32009-08-12 16:08:25 -0700191 // how long to wait before switching back to a radio's default network
192 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
193 // system property that can override the above value
194 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
195 "android.telephony.apn-restore";
196
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900197 // How long to wait before putting up a "This network doesn't have an Internet connection,
198 // connect anyway?" dialog after the user selects a network that doesn't validate.
199 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900201 // Default to 30s linger time-out. Modifiable only for testing.
202 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
203 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
204 @VisibleForTesting
205 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
206
Jeremy Joslin79294842014-12-03 17:15:28 -0800207 // How long to delay to removal of a pending intent based request.
208 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
209 private final int mReleasePendingIntentDelayMs;
210
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800211 private Tethering mTethering;
212
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700213 private final PermissionMonitor mPermissionMonitor;
214
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700215 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700216
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700217 @GuardedBy("mVpns")
218 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700219
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700220 private boolean mLockdownEnabled;
221 private LockdownVpnTracker mLockdownTracker;
222
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700223 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
224 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700227 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700228 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600229 @GuardedBy("mRulesLock")
230 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
231 /** Flag indicating if background data is restricted. */
232 @GuardedBy("mRulesLock")
233 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700234
Erik Klineda4bfa82015-04-30 12:58:40 +0900235 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700237 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800240 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700243 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800246 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700249 private String mCurrentTcpBufferSizes;
250
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251 private static final int ENABLED = 1;
252 private static final int DISABLED = 0;
253
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
256 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400259 // Tear down networks that have no chance (e.g. even if validated) of becoming
260 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 // all networks have been rematched against all NetworkRequests.
262 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Don't reap networks. This should be passed when some networks have not yet been
264 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 DONT_REAP
266 };
267
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900268 private enum UnneededFor {
269 LINGER, // Determine whether this network is unneeded and should be lingered.
270 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
271 }
272
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 * used internally to change our mobile data enabled flag
275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277
278 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700280 * from one net to another. Clear happens when we get a new
281 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
282 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286 /**
287 * used internally to reload global proxy settings
288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700291 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400292 * PAC manager has received new port.
293 */
294 private static final int EVENT_PROXY_HAS_CHANGED = 16;
295
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 /**
297 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700298 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 */
300 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
301
Robert Greenwalt7b816022014-04-18 15:25:25 -0700302 /**
303 * used internally when registering NetworkAgents
304 * obj = Messenger
305 */
306 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
307
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 /**
309 * used to add a network request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
313
314 /**
315 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900316 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 * cancel it.
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
321
322 /**
323 * used to add a network listener - no request
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
327
328 /**
329 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400330 * arg1 = UID of caller
331 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
334
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 /**
336 * used internally when registering NetworkFactories
337 * obj = Messenger
338 */
339 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
340
Robert Greenwalt27711812014-06-25 16:45:57 -0700341 /**
342 * used internally to expire a wakelock when transitioning
343 * from one net to another. Expire happens when we fail to find
344 * a new network (typically after 1 minute) -
345 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
346 * a replacement network.
347 */
348 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
349
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700350 /**
351 * Used internally to indicate the system is ready.
352 */
353 private static final int EVENT_SYSTEM_READY = 25;
354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 /**
356 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400357 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 */
359 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
360
361 /**
362 * used to remove a pending intent and its associated network request.
363 * arg1 = UID of caller
364 * obj = PendingIntent
365 */
366 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
367
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 /**
369 * used to specify whether a network should be used even if unvalidated.
370 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
371 * arg2 = whether to remember this choice in the future (1 or 0)
372 * obj = network
373 */
374 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
375
376 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900377 * used to specify whether a network should not be penalized when it becomes unvalidated.
378 */
379 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
380
381 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900382 * used to ask the user to confirm a connection to an unvalidated network.
383 * obj = network
384 */
385 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700386
Erik Klineda4bfa82015-04-30 12:58:40 +0900387 /**
388 * used internally to (re)configure mobile data always-on settings.
389 */
390 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
391
Paul Jensen694f2b82015-06-17 14:15:39 -0400392 /**
393 * used to add a network listener with a pending intent
394 * obj = NetworkRequestInfo
395 */
396 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
397
Erik Klineacdd6392016-07-07 16:50:58 +0900398 /**
399 * Indicates a caller has requested to have its callback invoked with
400 * the latest LinkProperties or NetworkCapabilities.
401 *
402 * arg1 = UID of caller
403 * obj = NetworkRequest
404 */
405 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
406 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
407
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900408 /** Handler thread used for both of the handlers below. */
409 @VisibleForTesting
410 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700411 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700412 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700413 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700414 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700415
Mike Lockwood0f79b542009-08-14 14:18:49 -0400416 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800417 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400418
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700419 private PowerManager.WakeLock mNetTransitionWakeLock;
420 private String mNetTransitionWakeLockCausedBy = "";
421 private int mNetTransitionWakeLockSerialNumber;
422 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800423 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700424
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700425 // used in DBG mode to track inet condition reports
426 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
427 private ArrayList mInetLog;
428
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400430 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700431 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700432 private boolean mDefaultProxyDisabled = false;
433
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400435 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436
Jason Monk602b2322013-07-03 17:04:33 -0400437 private PacManager mPacManager = null;
438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400441 private UserManager mUserManager;
442
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700443 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700444 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445
Robert Greenwalt50393202011-06-21 17:26:14 -0700446 // the set of network types that can only be enabled by system/sig apps
447 List mProtectedNetworks;
448
John Spurlockbf991a82013-06-24 14:20:23 -0400449 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700450
Wink Savilleab9321d2013-06-29 21:10:57 -0700451 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400452
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900454 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900455 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700457 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
458 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700459 private final static int MAX_NET_ID = 65535;
460 private int mNextNetId = MIN_NET_ID;
461
Robert Greenwalt34524f02014-05-18 16:22:10 -0700462 // sequence number of NetworkRequests
463 private int mNextNetworkRequestId = 1;
464
Erik Kline7523eb32015-07-09 18:24:03 +0900465 // NetworkRequest activity String log entries.
466 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
467 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
468
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 // NetworkInfo blocked and unblocked String log entries
470 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
471 private static final int MAX_NETWORK_INFO_LOGS = 100;
472 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
473
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700474 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
475 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400476 private static class ValidationLog {
477 final Network mNetwork;
478 final String mNetworkExtraInfo;
479 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
482 mNetwork = network;
483 mNetworkExtraInfo = networkExtraInfo;
484 mLog = log;
485 }
486 }
487 private final ArrayDeque<ValidationLog> mValidationLogs =
488 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
489
490 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700491 synchronized(mValidationLogs) {
492 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
493 mValidationLogs.removeLast();
494 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400495 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 }
497 }
498
Hugo Benichif9fdf872016-07-28 17:53:06 +0900499 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900500
Erik Kline065ab6e2016-10-02 18:02:14 +0900501 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900502 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900503
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700504 /**
505 * Implements support for the legacy "one network per network type" model.
506 *
507 * We used to have a static array of NetworkStateTrackers, one for each
508 * network type, but that doesn't work any more now that we can have,
509 * for example, more that one wifi network. This class stores all the
510 * NetworkAgentInfo objects that support a given type, but the legacy
511 * API will only see the first one.
512 *
513 * It serves two main purposes:
514 *
515 * 1. Provide information about "the network for a given type" (since this
516 * API only supports one).
517 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
518 * the first network for a given type changes, or if the default network
519 * changes.
520 */
521 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900523 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 /**
527 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
528 * Each list holds references to all NetworkAgentInfos that are used to
529 * satisfy requests for that network type.
530 *
531 * This array is built out at startup such that an unsupported network
532 * doesn't get an ArrayList instance, making this a tristate:
533 * unsupported, supported but not active and active.
534 *
535 * The actual lists are populated when we scan the network types that
536 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 *
538 * Threading model:
539 * - addSupportedType() is only called in the constructor
540 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
541 * They are therefore not thread-safe with respect to each other.
542 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
543 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
544 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900546 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700547
548 public LegacyTypeTracker() {
549 mTypeLists = (ArrayList<NetworkAgentInfo>[])
550 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
551 }
552
553 public void addSupportedType(int type) {
554 if (mTypeLists[type] != null) {
555 throw new IllegalStateException(
556 "legacy list for type " + type + "already initialized");
557 }
558 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
559 }
560
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 public boolean isTypeSupported(int type) {
562 return isNetworkTypeValid(type) && mTypeLists[type] != null;
563 }
564
565 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900566 synchronized (mTypeLists) {
567 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
568 return mTypeLists[type].get(0);
569 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900571 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 }
573
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900578 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 }
581 }
582
583 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 public void add(int type, NetworkAgentInfo nai) {
585 if (!isTypeSupported(type)) {
586 return; // Invalid network type.
587 }
588 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
589
590 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
591 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 return;
593 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 synchronized (mTypeLists) {
595 list.add(nai);
596 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900597
598 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900599 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900600 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
602 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700604 }
605
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900607 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list == null || list.isEmpty()) {
610 return;
611 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 synchronized (mTypeLists) {
615 if (!list.remove(nai)) {
616 return;
617 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 final DetailedState state = DetailedState.DISCONNECTED;
621
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(nai, state, type, wasDefault);
624 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626
627 if (!list.isEmpty() && wasFirstNetwork) {
628 if (DBG) log("Other network available for type " + type +
629 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700631 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
632 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 }
634 }
635
636 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
638 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700639 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
642 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700643
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 // send out another legacy broadcast - currently only used for suspend/unsuspend
645 // toggle
646 public void update(NetworkAgentInfo nai) {
647 final boolean isDefault = isDefaultNetwork(nai);
648 final DetailedState state = nai.networkInfo.getDetailedState();
649 for (int type = 0; type < mTypeLists.length; type++) {
650 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700651 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 final boolean isFirst = contains && (nai == list.get(0));
653 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700654 maybeLogBroadcast(nai, state, type, isDefault);
655 sendLegacyNetworkBroadcast(nai, state, type);
656 }
657 }
658 }
659
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 private String naiToString(NetworkAgentInfo nai) {
661 String name = (nai != null) ? nai.name() : "null";
662 String state = (nai.networkInfo != null) ?
663 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
664 "???/???";
665 return name + " " + state;
666 }
667
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println("mLegacyTypeTracker:");
670 pw.increaseIndent();
671 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 pw.println();
676 pw.println("Current state:");
677 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 synchronized (mTypeLists) {
679 for (int type = 0; type < mTypeLists.length; type++) {
680 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
681 for (NetworkAgentInfo nai : mTypeLists[type]) {
682 pw.println(type + " " + naiToString(nai));
683 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900684 }
685 }
686 pw.decreaseIndent();
687 pw.decreaseIndent();
688 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700689 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
692
Jeff Sharkey899223b2012-08-04 15:24:58 -0700693 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700694 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900695 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
696 }
697
698 @VisibleForTesting
699 protected ConnectivityService(Context context, INetworkManagementService netManager,
700 INetworkStatsService statsService, INetworkPolicyManager policyManager,
701 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800703
Hugo Benichif9fdf872016-07-28 17:53:06 +0900704 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900705 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900706 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900707 mNetworkRequests.put(mDefaultRequest, defaultNRI);
708 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900709
710 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900711 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700712
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900713 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900714 mHandlerThread.start();
715 mHandler = new InternalHandler(mHandlerThread.getLooper());
716 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700717
Jeremy Joslin79294842014-12-03 17:15:28 -0800718 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
719 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
720
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900721 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
722
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700723 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700724 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800725 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700727 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700728 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700729
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600731 mPolicyManager.setConnectivityListener(mPolicyListener);
732 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700733 } catch (RemoteException e) {
734 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700735 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 }
737
738 final PowerManager powerManager = (PowerManager) context.getSystemService(
739 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700740 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
741 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
742 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800743 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700745 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746
Wink Saville51f456f2013-04-23 14:26:51 -0700747 // TODO: What is the "correct" way to do determine if this is a wifi only device?
748 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
749 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 String[] naStrings = context.getResources().getStringArray(
751 com.android.internal.R.array.networkAttributes);
752 for (String naString : naStrings) {
753 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700754 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700755 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700756 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800757 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700758 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700760 }
Wink Saville51f456f2013-04-23 14:26:51 -0700761 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
762 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
763 n.type);
764 continue;
765 }
Wink Saville975c8482011-04-07 14:23:45 -0700766 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800767 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700768 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769 continue;
770 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700771 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700772
Wink Saville975c8482011-04-07 14:23:45 -0700773 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 mNetworksDefined++;
775 } catch(Exception e) {
776 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700777 }
778 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700779
780 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
781 if (mNetConfigs[TYPE_VPN] == null) {
782 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
783 // don't need to add TYPE_VPN to mNetConfigs.
784 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
785 mNetworksDefined++; // used only in the log() statement below.
786 }
787
Wink Saville5e56bc52013-07-29 15:00:57 -0700788 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700789
Robert Greenwalt50393202011-06-21 17:26:14 -0700790 mProtectedNetworks = new ArrayList<Integer>();
791 int[] protectedNetworks = context.getResources().getIntArray(
792 com.android.internal.R.array.config_protectedNetworks);
793 for (int p : protectedNetworks) {
794 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
795 mProtectedNetworks.add(p);
796 } else {
797 if (DBG) loge("Ignoring protectedNetwork " + p);
798 }
799 }
800
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700801 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
802 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700803
Christopher Wiley497c1472016-10-11 13:26:03 -0700804 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
805 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800806
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700807 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
808
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700809 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700810 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100811 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700812 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700813 intentFilter.addAction(Intent.ACTION_USER_ADDED);
814 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000815 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700816 mContext.registerReceiverAsUser(
817 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000818 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
819 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900820
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700821 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700822 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700823 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700824 } catch (RemoteException e) {
825 loge("Error registering observer :" + e);
826 }
827
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700828 if (DBG) {
829 mInetLog = new ArrayList();
830 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700831
Erik Klineda4bfa82015-04-30 12:58:40 +0900832 mSettingsObserver = new SettingsObserver(mContext, mHandler);
833 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800834
John Spurlockbf991a82013-06-24 14:20:23 -0400835 mDataConnectionStats = new DataConnectionStats(mContext);
836 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400837
Jason Monkdecd2952013-10-10 14:02:51 -0400838 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700839
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400840 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900841
842 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900843 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
844 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900845
846 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
847 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
848 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
849 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
850 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
851 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
852 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900853
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900854 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900855 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900856 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700858
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900859 private NetworkRequest createInternetRequestForTransport(
860 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900862 netCap.addCapability(NET_CAPABILITY_INTERNET);
863 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900864 if (transportType > -1) {
865 netCap.addTransportType(transportType);
866 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900867 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900868 }
869
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900870 // Used only for testing.
871 // TODO: Delete this and either:
872 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
873 // changing ContentResolver to make registerContentObserver non-final).
874 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
875 // by subclassing SettingsObserver.
876 @VisibleForTesting
877 void updateMobileDataAlwaysOn() {
878 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
879 }
880
Erik Klineda4bfa82015-04-30 12:58:40 +0900881 private void handleMobileDataAlwaysOn() {
882 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900883 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900884 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
885 if (enable == isEnabled) {
886 return; // Nothing to do.
887 }
888
889 if (enable) {
890 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900891 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 } else {
893 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
894 }
895 }
896
897 private void registerSettingsCallbacks() {
898 // Watch for global HTTP proxy changes.
899 mSettingsObserver.observe(
900 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
901 EVENT_APPLY_GLOBAL_HTTP_PROXY);
902
903 // Watch for whether or not to keep mobile data always on.
904 mSettingsObserver.observe(
905 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
906 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
907 }
908
Robert Greenwalt34524f02014-05-18 16:22:10 -0700909 private synchronized int nextNetworkRequestId() {
910 return mNextNetworkRequestId++;
911 }
912
Paul Jensen67b0b072015-06-10 11:22:17 -0400913 @VisibleForTesting
914 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400915 synchronized (mNetworkForNetId) {
916 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
917 int netId = mNextNetId;
918 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
919 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500920 if (!mNetIdInUse.get(netId)) {
921 mNetIdInUse.put(netId, true);
922 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400923 }
924 }
925 }
926 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700927 }
928
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600929 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600931 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
932 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 state = nai.getNetworkState();
935 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 final NetworkInfo info = new NetworkInfo(networkType, 0,
938 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
940 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600941 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
942 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600944 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 return state;
946 } else {
947 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400949 }
950
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
952 if (network == null) {
953 return null;
954 }
955 synchronized (mNetworkForNetId) {
956 return mNetworkForNetId.get(network.netId);
957 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600958 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900960 private Network[] getVpnUnderlyingNetworks(int uid) {
961 if (!mLockdownEnabled) {
962 int user = UserHandle.getUserId(uid);
963 synchronized (mVpns) {
964 Vpn vpn = mVpns.get(user);
965 if (vpn != null && vpn.appliesToUid(uid)) {
966 return vpn.getUnderlyingNetworks();
967 }
968 }
969 }
970 return null;
971 }
972
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400974 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800975
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900976 final Network[] networks = getVpnUnderlyingNetworks(uid);
977 if (networks != null) {
978 // getUnderlyingNetworks() returns:
979 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
980 // empty array => the VPN explicitly said "no default network".
981 // non-empty array => the VPN specified one or more default networks; we use the
982 // first one.
983 if (networks.length > 0) {
984 nai = getNetworkAgentInfoForNetwork(networks[0]);
985 } else {
986 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800987 }
988 }
989
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600991 return nai.getNetworkState();
992 } else {
993 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400995 }
996
997 /**
998 * Check if UID should be blocked from using the network with the given LinkProperties.
999 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1001 boolean ignoreBlocked) {
1002 // Networks aren't blocked when ignoring blocked status
1003 if (ignoreBlocked) return false;
1004 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001005 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001006
1007 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001008 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001009
Robin Lee17e61832016-05-09 13:46:28 +01001010 synchronized (mVpns) {
1011 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1012 if (vpn != null && vpn.isBlockingUid(uid)) {
1013 return true;
1014 }
1015 }
1016
Robert Greenwalt12e67352014-05-13 21:41:06 -07001017 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001018 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001019 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001020 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001022
Felipe Lemed31a97f2016-05-06 14:53:50 -07001023 boolean allowed = true;
1024 // Check Data Saver Mode first...
1025 if (networkMetered) {
1026 if ((uidRules & RULE_REJECT_METERED) != 0) {
1027 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1028 // Explicitly blacklisted.
1029 allowed = false;
1030 } else {
1031 allowed = !mRestrictBackground
1032 || (uidRules & RULE_ALLOW_METERED) != 0
1033 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1034 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1035 + " mRestrictBackground=" + mRestrictBackground
1036 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1037 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1038 + ": " + allowed);
1039 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001040 }
Felipe Leme781ba142016-05-09 16:24:48 -07001041 // ...then power restrictions.
1042 if (allowed) {
1043 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001044 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001045 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001046 }
1047 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001048 }
1049
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001050 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001051 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1052 return;
1053 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001054 boolean removed = false;
1055 boolean added = false;
1056 synchronized (mBlockedAppUids) {
1057 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1058 added = true;
1059 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1060 removed = true;
1061 }
1062 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001063 if (added) {
1064 log("Returning blocked NetworkInfo to uid=" + uid);
1065 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1066 } else if (removed) {
1067 log("Returning unblocked NetworkInfo to uid=" + uid);
1068 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1069 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001070 }
1071
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001072 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1074 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1075 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1076 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001077 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001078 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001079 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1080
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001083 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 if (mLockdownTracker != null) {
1085 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001086 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087
1088 // TODO: apply metered state closer to NetworkAgentInfo
1089 final long token = Binder.clearCallingIdentity();
1090 try {
1091 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1092 } catch (RemoteException e) {
1093 } finally {
1094 Binder.restoreCallingIdentity(token);
1095 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001096 }
1097
1098 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 * Return NetworkInfo for the active (i.e., connected) network interface.
1100 * It is assumed that at most one network is active at a time. If more
1101 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001102 * @return the info for the active network, or {@code null} if none is
1103 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001107 enforceAccessPermission();
1108 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001111 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1112 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
1114
Paul Jensen31a94f42015-02-13 14:18:39 -05001115 @Override
1116 public Network getActiveNetwork() {
1117 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001118 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001119 }
1120
1121 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001123 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001124 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001125 }
1126
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001128 final int user = UserHandle.getUserId(uid);
1129 int vpnNetId = NETID_UNSET;
1130 synchronized (mVpns) {
1131 final Vpn vpn = mVpns.get(user);
1132 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1133 }
1134 NetworkAgentInfo nai;
1135 if (vpnNetId != NETID_UNSET) {
1136 synchronized (mNetworkForNetId) {
1137 nai = mNetworkForNetId.get(vpnNetId);
1138 }
1139 if (nai != null) return nai.network;
1140 }
1141 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 if (nai != null
1143 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1144 nai = null;
1145 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001146 return nai != null ? nai.network : null;
1147 }
1148
Lorenzo Colitti18660282016-07-04 12:55:44 +09001149 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001150 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1151 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 final int uid = Binder.getCallingUid();
1153 NetworkState state = getUnfilteredActiveNetworkState(uid);
1154 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001155 }
1156
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 }
1164
1165 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 public NetworkInfo getNetworkInfo(int networkType) {
1167 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001168 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001169 if (getVpnUnderlyingNetworks(uid) != null) {
1170 // A VPN is active, so we may need to return one of its underlying networks. This
1171 // information is not available in LegacyTypeTracker, so we have to get it from
1172 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001174 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001177 }
1178 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001189 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001190 return state.networkInfo;
1191 } else {
1192 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001193 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001194 }
1195
1196 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 public NetworkInfo[] getAllNetworkInfo() {
1198 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001200 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1201 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 NetworkInfo info = getNetworkInfo(networkType);
1203 if (info != null) {
1204 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001207 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001210 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001211 public Network getNetworkForType(int networkType) {
1212 enforceAccessPermission();
1213 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001214 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1215 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001219 }
1220
1221 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 public Network[] getAllNetworks() {
1223 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001225 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001227 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001229 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 }
1232
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001233 @Override
1234 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1235 // The basic principle is: if an app's traffic could possibly go over a
1236 // network, without the app doing anything multinetwork-specific,
1237 // (hence, by "default"), then include that network's capabilities in
1238 // the array.
1239 //
1240 // In the normal case, app traffic only goes over the system's default
1241 // network connection, so that's the only network returned.
1242 //
1243 // With a VPN in force, some app traffic may go into the VPN, and thus
1244 // over whatever underlying networks the VPN specifies, while other app
1245 // traffic may go over the system default network (e.g.: a split-tunnel
1246 // VPN, or an app disallowed by the VPN), so the set of networks
1247 // returned includes the VPN's underlying networks and the system
1248 // default.
1249 enforceAccessPermission();
1250
1251 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1252
1253 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001254 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001255 if (nc != null) {
1256 result.put(nai.network, nc);
1257 }
1258
1259 if (!mLockdownEnabled) {
1260 synchronized (mVpns) {
1261 Vpn vpn = mVpns.get(userId);
1262 if (vpn != null) {
1263 Network[] networks = vpn.getUnderlyingNetworks();
1264 if (networks != null) {
1265 for (Network network : networks) {
1266 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001267 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001268 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001269 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001270 }
1271 }
1272 }
1273 }
1274 }
1275 }
1276
1277 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1278 out = result.values().toArray(out);
1279 return out;
1280 }
1281
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001283 public boolean isNetworkSupported(int networkType) {
1284 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001285 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001286 }
1287
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001288 /**
1289 * Return LinkProperties for the active (i.e., connected) default
1290 * network interface. It is assumed that at most one default network
1291 * is active at a time. If more than one is active, it is indeterminate
1292 * which will be returned.
1293 * @return the ip properties for the active network, or {@code null} if
1294 * none is active
1295 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001296 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001297 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001298 enforceAccessPermission();
1299 final int uid = Binder.getCallingUid();
1300 NetworkState state = getUnfilteredActiveNetworkState(uid);
1301 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001302 }
1303
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001304 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001305 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001306 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001307 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1308 if (nai != null) {
1309 synchronized (nai) {
1310 return new LinkProperties(nai.linkProperties);
1311 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001312 }
1313 return null;
1314 }
1315
Robert Greenwalt12e67352014-05-13 21:41:06 -07001316 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001317 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001318 public LinkProperties getLinkProperties(Network network) {
1319 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001320 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 if (nai != null) {
1322 synchronized (nai) {
1323 return new LinkProperties(nai.linkProperties);
1324 }
1325 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001326 return null;
1327 }
1328
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001329 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001330 if (nai != null) {
1331 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 if (nai.networkCapabilities != null) {
1333 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001334 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001335 }
1336 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001337 return null;
1338 }
1339
1340 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001341 public NetworkCapabilities getNetworkCapabilities(Network network) {
1342 enforceAccessPermission();
1343 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1344 }
1345
1346 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001347 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001348 // Require internal since we're handing out IMSI details
1349 enforceConnectivityInternalPermission();
1350
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001351 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001352 for (Network network : getAllNetworks()) {
1353 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1354 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001355 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001356 }
1357 }
1358 return result.toArray(new NetworkState[result.size()]);
1359 }
1360
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001361 @Override
1362 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1363 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001364 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001365 final long token = Binder.clearCallingIdentity();
1366 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1368 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001369 try {
1370 return mPolicyManager.getNetworkQuotaInfo(state);
1371 } catch (RemoteException e) {
1372 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001373 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001374 return null;
1375 } finally {
1376 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001377 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001378 }
1379
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001380 @Override
1381 public boolean isActiveNetworkMetered() {
1382 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001383
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001384 final NetworkInfo info = getActiveNetworkInfo();
1385 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001386 }
1387
Jeff Sharkey216c1812012-08-05 14:29:23 -07001388 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1389 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001390 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001391 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001392 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001393 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001394 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001395
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001396 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 * Ensure that a network route exists to deliver traffic to the specified
1398 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001399 * @param networkType the type of the network over which traffic to the
1400 * specified host is to be routed
1401 * @param hostAddress the IP address of the host to which the route is
1402 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 * @return {@code true} on success, {@code false} on failure
1404 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001405 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001406 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001408 if (mProtectedNetworks.contains(networkType)) {
1409 enforceConnectivityInternalPermission();
1410 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001411
Chad Brubakerc0234532014-02-14 13:24:29 -08001412 InetAddress addr;
1413 try {
1414 addr = InetAddress.getByAddress(hostAddress);
1415 } catch (UnknownHostException e) {
1416 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1417 return false;
1418 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001421 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 return false;
1423 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001424
1425 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1426 if (nai == null) {
1427 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1428 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1429 } else {
1430 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1431 }
1432 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001433 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001434
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001435 DetailedState netState;
1436 synchronized (nai) {
1437 netState = nai.networkInfo.getDetailedState();
1438 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001439
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001440 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001441 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001442 log("requestRouteToHostAddress on down network "
1443 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001444 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001445 }
1446 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001448
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001449 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001450 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001451 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001452 LinkProperties lp;
1453 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001454 synchronized (nai) {
1455 lp = nai.linkProperties;
1456 netId = nai.network.netId;
1457 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001458 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001459 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1460 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001461 } finally {
1462 Binder.restoreCallingIdentity(token);
1463 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001464 }
1465
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001466 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001467 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001469 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001471 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001472 if (bestRoute.getGateway().equals(addr)) {
1473 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001474 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001475 } else {
1476 // if we will connect to this through another route, add a direct route
1477 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001478 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001479 }
1480 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001481 if (DBG) log("Adding legacy route " + bestRoute +
1482 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001483 try {
1484 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1485 } catch (Exception e) {
1486 // never crash - catch them all
1487 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001488 return false;
1489 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001490 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001493 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1494 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001495 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001496 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001498 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001499 }
1500
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001501 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001503 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001504 if (oldRules == uidRules) return;
1505
Felipe Leme781ba142016-05-09 16:24:48 -07001506 if (uidRules == RULE_NONE) {
1507 mUidRules.delete(uid);
1508 } else {
1509 mUidRules.put(uid, uidRules);
1510 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 }
1512
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001513 // TODO: notify UID when it has requested targeted updates
1514 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001515
1516 @Override
1517 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001518 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001519 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001520 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001521 }
1522
1523 synchronized (mRulesLock) {
1524 mMeteredIfaces.clear();
1525 for (String iface : meteredIfaces) {
1526 mMeteredIfaces.add(iface);
1527 }
1528 }
1529 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001530
1531 @Override
1532 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1533 // caller is NPMS, since we only register with them
1534 if (LOGD_RULES) {
1535 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1536 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001537
1538 synchronized (mRulesLock) {
1539 mRestrictBackground = restrictBackground;
1540 }
1541
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001542 if (restrictBackground) {
1543 log("onRestrictBackgroundChanged(true): disabling tethering");
1544 mTethering.untetherAll();
1545 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001546 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001547
1548 @Override
1549 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1550 if (LOGD_RULES) {
1551 // caller is NPMS, since we only register with them
1552 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1553 + whitelisted + ")");
1554 }
1555 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001556 @Override
1557 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1558 if (LOGD_RULES) {
1559 // caller is NPMS, since we only register with them
1560 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1561 + blacklisted + ")");
1562 }
1563 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001564 };
1565
Robin Lee3b3dd942015-05-12 18:14:58 +01001566 /**
1567 * Require that the caller is either in the same user or has appropriate permission to interact
1568 * across users.
1569 *
1570 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1571 */
1572 private void enforceCrossUserPermission(int userId) {
1573 if (userId == UserHandle.getCallingUserId()) {
1574 // Not a cross-user call.
1575 return;
1576 }
1577 mContext.enforceCallingOrSelfPermission(
1578 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1579 "ConnectivityService");
1580 }
1581
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001582 private void enforceInternetPermission() {
1583 mContext.enforceCallingOrSelfPermission(
1584 android.Manifest.permission.INTERNET,
1585 "ConnectivityService");
1586 }
1587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001589 mContext.enforceCallingOrSelfPermission(
1590 android.Manifest.permission.ACCESS_NETWORK_STATE,
1591 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
1593
1594 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001595 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001598 private void enforceTetherAccessPermission() {
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.ACCESS_NETWORK_STATE,
1601 "ConnectivityService");
1602 }
1603
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001604 private void enforceConnectivityInternalPermission() {
1605 mContext.enforceCallingOrSelfPermission(
1606 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1607 "ConnectivityService");
1608 }
1609
Hugo Benichi514da602016-07-19 15:59:27 +09001610 private void enforceConnectivityRestrictedNetworksPermission() {
1611 try {
1612 mContext.enforceCallingOrSelfPermission(
1613 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1614 "ConnectivityService");
1615 return;
1616 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1617 enforceConnectivityInternalPermission();
1618 }
1619
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001620 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001621 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001622 }
1623
Lorenzo Colitti18660282016-07-04 12:55:44 +09001624 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001625 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001626 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001627 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001628 }
1629
1630 private void sendInetConditionBroadcast(NetworkInfo info) {
1631 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1632 }
1633
Wink Saville628b0852011-08-04 15:01:58 -07001634 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001635 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001636 info = new NetworkInfo(info);
1637 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001638 }
1639
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001640 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001641 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001642 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 if (info.isFailover()) {
1644 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1645 info.setFailover(false);
1646 }
1647 if (info.getReason() != null) {
1648 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1649 }
1650 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001651 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1652 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001654 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001655 return intent;
1656 }
1657
1658 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1659 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1660 }
1661
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001662 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001663 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1664 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1665 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001666 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001667 final long ident = Binder.clearCallingIdentity();
1668 try {
1669 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1670 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1671 } finally {
1672 Binder.restoreCallingIdentity(ident);
1673 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001674 }
1675
Mike Lockwood0f79b542009-08-14 14:18:49 -04001676 private void sendStickyBroadcast(Intent intent) {
1677 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001678 if (!mSystemReady) {
1679 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001680 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001681 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001682 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001683 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001684 }
1685
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001686 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001687 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001688 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001689 final NetworkInfo ni = intent.getParcelableExtra(
1690 ConnectivityManager.EXTRA_NETWORK_INFO);
1691 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1692 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1693 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001694 } else {
1695 BroadcastOptions opts = BroadcastOptions.makeBasic();
1696 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1697 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001698 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001699 final IBatteryStats bs = BatteryStatsService.getService();
1700 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001701 bs.noteConnectivityChanged(intent.getIntExtra(
1702 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1703 ni != null ? ni.getState().toString() : "?");
1704 } catch (RemoteException e) {
1705 }
1706 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001708 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001709 } finally {
1710 Binder.restoreCallingIdentity(ident);
1711 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001712 }
1713 }
1714
1715 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001716 loadGlobalProxy();
1717
Mike Lockwood0f79b542009-08-14 14:18:49 -04001718 synchronized(this) {
1719 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001720 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001721 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001722 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001723 }
1724 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001725 // load the global proxy at startup
1726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001727
Robin Lee244ce8e2016-01-05 18:03:46 +00001728 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1729 // for user to unlock device too.
1730 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001731
Erik Klineda4bfa82015-04-30 12:58:40 +09001732 // Configure whether mobile data is always on.
1733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1734
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001736
1737 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001741 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001742 *
1743 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001744 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001745 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1747 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001748
1749 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001751
Robert Greenwalt7b816022014-04-18 15:25:25 -07001752 if (networkAgent.networkCapabilities.hasTransport(
1753 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001754 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1755 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001756 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001757 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001758 } else if (networkAgent.networkCapabilities.hasTransport(
1759 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001760 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1761 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001762 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001763 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001764 } else {
1765 // do not track any other networks
1766 timeout = 0;
1767 }
1768
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001770 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001771 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001772 } catch (Exception e) {
1773 // You shall not crash!
1774 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001775 }
1776 }
1777 }
1778
1779 /**
1780 * Remove data activity tracking when network disconnects.
1781 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001782 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1783 final String iface = networkAgent.linkProperties.getInterfaceName();
1784 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001785
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1787 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001788 try {
1789 // the call fails silently if no idletimer setup for this interface
1790 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001791 } catch (Exception e) {
1792 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001793 }
1794 }
1795 }
1796
1797 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001798 * Reads the network specific MTU size from reources.
1799 * and set it on it's iface.
1800 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001801 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1802 final String iface = newLp.getInterfaceName();
1803 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001804 if (oldLp == null && mtu == 0) {
1805 // Silently ignore unset MTU value.
1806 return;
1807 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001808 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1809 if (VDBG) log("identical MTU - not setting");
1810 return;
1811 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001812 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001813 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001814 return;
1815 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001816
w1997615afd812014-08-05 15:18:11 -07001817 // Cannot set MTU without interface name
1818 if (TextUtils.isEmpty(iface)) {
1819 loge("Setting MTU size with null iface.");
1820 return;
1821 }
1822
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001824 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001825 mNetd.setMtu(iface, mtu);
1826 } catch (Exception e) {
1827 Slog.e(TAG, "exception in setMtu()" + e);
1828 }
1829 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001831 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001832 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1833
1834 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001835 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001836 protected int getDefaultTcpRwnd() {
1837 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1838 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001839
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1841 if (isDefaultNetwork(nai) == false) {
1842 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001843 }
1844
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1846 String[] values = null;
1847 if (tcpBufferSizes != null) {
1848 values = tcpBufferSizes.split(",");
1849 }
1850
1851 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001852 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001853 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1854 values = tcpBufferSizes.split(",");
1855 }
1856
1857 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1858
1859 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001860 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001861
1862 final String prefix = "/sys/kernel/ipv4/tcp_";
1863 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1864 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1865 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1866 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1867 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1868 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1869 mCurrentTcpBufferSizes = tcpBufferSizes;
1870 } catch (IOException e) {
1871 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001873
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001875 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001876 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1877 if (rwndValue != 0) {
1878 SystemProperties.set(sysctlKey, rwndValue.toString());
1879 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001880 }
1881
Mattias Falk8b47b362011-08-23 14:15:13 +02001882 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001883 /*
1884 * Tell the VMs to toss their DNS caches
1885 */
1886 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1887 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001888 /*
1889 * Connectivity events can happen before boot has completed ...
1890 */
1891 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001892 final long ident = Binder.clearCallingIdentity();
1893 try {
1894 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1895 } finally {
1896 Binder.restoreCallingIdentity(ident);
1897 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001898 }
1899
Robert Greenwalt562cc542014-05-15 18:07:26 -07001900 @Override
1901 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1903 NETWORK_RESTORE_DELAY_PROP_NAME);
1904 if(restoreDefaultNetworkDelayStr != null &&
1905 restoreDefaultNetworkDelayStr.length() != 0) {
1906 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001907 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001908 } catch (NumberFormatException e) {
1909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001911 // if the system property isn't set, use the value for the apn type
1912 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1913
1914 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1915 (mNetConfigs[networkType] != null)) {
1916 ret = mNetConfigs[networkType].restoreTime;
1917 }
1918 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001921 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001922 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001923 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001924 }
1925 return false;
1926 }
1927
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001928 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1929 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1930 final long DIAG_TIME_MS = 5000;
1931 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1932 // Start gathering diagnostic information.
1933 netDiags.add(new NetworkDiagnostics(
1934 nai.network,
1935 new LinkProperties(nai.linkProperties), // Must be a copy.
1936 DIAG_TIME_MS));
1937 }
1938
1939 for (NetworkDiagnostics netDiag : netDiags) {
1940 pw.println();
1941 netDiag.waitForMeasurements();
1942 netDiag.dump(pw);
1943 }
1944 }
1945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001947 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1948 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001949 if (mContext.checkCallingOrSelfPermission(
1950 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001952 pw.println("Permission Denial: can't dump ConnectivityService " +
1953 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1954 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 return;
1956 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001958 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001959 dumpNetworkDiagnostics(pw);
1960 return;
1961 }
Erik Kline379747a2015-06-05 17:47:34 +09001962
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001965 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001966 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001967 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001968 pw.println();
1969
Paul Jensen85cf78e2015-06-25 13:25:07 -04001970 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.print("Active default network: ");
1972 if (defaultNai == null) {
1973 pw.println("none");
1974 } else {
1975 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001977 pw.println();
1978
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001980 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1982 pw.println(nai.toString());
1983 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001984 pw.println(String.format(
1985 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1986 nai.numForegroundNetworkRequests(),
1987 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1988 nai.numBackgroundNetworkRequests(),
1989 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001991 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1992 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001993 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 pw.decreaseIndent();
1995 pw.println("Lingered:");
1996 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001997 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001998 pw.decreaseIndent();
1999 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002000 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002001 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002002 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002003
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002004 pw.println("Metered Interfaces:");
2005 pw.increaseIndent();
2006 for (String value : mMeteredIfaces) {
2007 pw.println(value);
2008 }
2009 pw.decreaseIndent();
2010 pw.println();
2011
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002012 pw.print("Restrict background: ");
2013 pw.println(mRestrictBackground);
2014 pw.println();
2015
Felipe Leme46c4fc32016-05-04 09:21:43 -07002016 pw.println("Status for known UIDs:");
2017 pw.increaseIndent();
2018 final int size = mUidRules.size();
2019 for (int i = 0; i < size; i++) {
2020 final int uid = mUidRules.keyAt(i);
2021 pw.print("UID=");
2022 pw.print(uid);
2023 final int uidRules = mUidRules.get(uid, RULE_NONE);
2024 pw.print(" rules=");
2025 pw.print(uidRulesToString(uidRules));
2026 pw.println();
2027 }
2028 pw.println();
2029 pw.decreaseIndent();
2030
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002031 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002032 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002033 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2034 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002035 }
2036 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002037 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002038
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002039 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002040
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002041 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002042 pw.print("mNetTransitionWakeLock: currently " +
2043 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2044 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2045 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2046 } else {
2047 pw.println(", last requested never");
2048 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002049 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002050
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002051 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002052 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002053
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002054 pw.println();
2055 mKeepaliveTracker.dump(pw);
2056
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002057 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002058 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002059
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002060 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002061 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002062 pw.println();
2063 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002064 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002065 for(int i = 0; i < mInetLog.size(); i++) {
2066 pw.println(mInetLog.get(i));
2067 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002068 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002069 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002070
2071 if (argsContain(args, "--short") == false) {
2072 pw.println();
2073 synchronized (mValidationLogs) {
2074 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002075 for (ValidationLog p : mValidationLogs) {
2076 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002077 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002078 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002079 pw.decreaseIndent();
2080 }
2081 }
Erik Kline7523eb32015-07-09 18:24:03 +09002082
2083 pw.println();
2084 pw.println("mNetworkRequestInfoLogs (most recent first):");
2085 pw.increaseIndent();
2086 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2087 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002088
2089 pw.println();
2090 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2091 pw.increaseIndent();
2092 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2093 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002097 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002098 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002099 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002100 if (officialNai != null && officialNai.equals(nai)) return true;
2101 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002102 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002103 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002104 " - " + nai);
2105 }
2106 return false;
2107 }
2108
Robert Greenwalt42acef32009-08-12 16:08:25 -07002109 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002110 private class NetworkStateTrackerHandler extends Handler {
2111 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002112 super(looper);
2113 }
2114
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002117 default:
2118 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002119 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 handleAsyncChannelHalfConnect(msg);
2121 break;
2122 }
2123 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2124 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2125 if (nai != null) nai.asyncChannel.disconnect();
2126 break;
2127 }
2128 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2129 handleAsyncChannelDisconnected(msg);
2130 break;
2131 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002132 }
2133 return true;
2134 }
2135
2136 private void maybeHandleNetworkAgentMessage(Message msg) {
2137 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2138 if (nai == null) {
2139 if (VDBG) {
2140 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2141 log(String.format("%s from unknown NetworkAgent", what));
2142 }
2143 return;
2144 }
2145
2146 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002148 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2149 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002150 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2151 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002153 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002154 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002155 break;
2156 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002157 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002158 if (VDBG) {
2159 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002160 "; created=" + nai.created +
2161 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002163 LinkProperties oldLp = nai.linkProperties;
2164 synchronized (nai) {
2165 nai.linkProperties = (LinkProperties)msg.obj;
2166 }
Robin Lee585e2482016-05-01 23:00:00 +01002167 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002168 break;
2169 }
2170 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002171 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002172 updateNetworkInfo(nai, info);
2173 break;
2174 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002175 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002176 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002177 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002178 break;
2179 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002180 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002181 try {
2182 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002183 } catch (Exception e) {
2184 // Never crash!
2185 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002186 }
2187 break;
2188 }
2189 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002190 try {
2191 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002192 } catch (Exception e) {
2193 // Never crash!
2194 loge("Exception in removeVpnUidRanges: " + e);
2195 }
2196 break;
2197 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002199 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2200 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002201 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002202 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002203 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002204 break;
2205 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002206 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002207 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2208 break;
2209 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002210 }
2211 }
2212
2213 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2214 switch (msg.what) {
2215 default:
2216 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002217 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002218 final NetworkAgentInfo nai;
2219 synchronized (mNetworkForNetId) {
2220 nai = mNetworkForNetId.get(msg.arg2);
2221 }
2222 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002223 final boolean valid =
2224 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002225 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002226 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2227 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002228 if (valid != nai.lastValidated) {
2229 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002230 nai.lastValidated = valid;
2231 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002232 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002233 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2234 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002235 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002236 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002237 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002238 Bundle redirectUrlBundle = new Bundle();
2239 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002240 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002241 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002242 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002243 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002244 if (wasValidated && !nai.lastValidated) {
2245 handleNetworkUnvalidated(nai);
2246 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002247 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002248 break;
2249 }
Paul Jensen869868be2014-05-15 10:33:05 -04002250 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002251 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 final boolean visible = (msg.arg1 != 0);
2253 final NetworkAgentInfo nai;
2254 synchronized (mNetworkForNetId) {
2255 nai = mNetworkForNetId.get(netId);
2256 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002257 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002258 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002259 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002260 nai.lastCaptivePortalDetected = visible;
2261 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002262 if (nai.lastCaptivePortalDetected &&
2263 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2264 if (DBG) log("Avoiding captive portal network: " + nai.name());
2265 nai.asyncChannel.sendMessage(
2266 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2267 teardownUnneededNetwork(nai);
2268 break;
2269 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002270 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002271 }
2272 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002273 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002274 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002275 if (nai == null) {
2276 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2277 break;
2278 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002279 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002280 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002281 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002282 }
Paul Jensen869868be2014-05-15 10:33:05 -04002283 }
Paul Jensen869868be2014-05-15 10:33:05 -04002284 break;
2285 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002286 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002287 return true;
2288 }
2289
Calvin On1f64f3f2016-10-11 15:10:46 -07002290 private int getCaptivePortalMode() {
2291 return Settings.Global.getInt(mContext.getContentResolver(),
2292 Settings.Global.CAPTIVE_PORTAL_MODE,
2293 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2294 }
2295
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2297 switch (msg.what) {
2298 default:
2299 return false;
2300 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2301 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2302 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2303 handleLingerComplete(nai);
2304 }
2305 break;
2306 }
2307 }
2308 return true;
2309 }
2310
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002311 @Override
2312 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002313 if (!maybeHandleAsyncChannelMessage(msg) &&
2314 !maybeHandleNetworkMonitorMessage(msg) &&
2315 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002316 maybeHandleNetworkAgentMessage(msg);
2317 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002318 }
2319 }
2320
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002321 private void updateLingerState(NetworkAgentInfo nai, long now) {
2322 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2323 // 2. If the network was lingering and there are now requests, unlinger it.
2324 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2325 // one lingered request, start lingering.
2326 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002327 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002328 if (DBG) log("Unlingering " + nai.name());
2329 nai.unlinger();
2330 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002331 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002332 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002333 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002334 nai.linger();
2335 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2336 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2337 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002338 }
2339
Robert Greenwalt7b816022014-04-18 15:25:25 -07002340 private void handleAsyncChannelHalfConnect(Message msg) {
2341 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002342 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002343 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2344 if (VDBG) log("NetworkFactory connected");
2345 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002347 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002349 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002350 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 }
2352 } else {
2353 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002354 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002355 }
2356 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2357 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2358 if (VDBG) log("NetworkAgent connected");
2359 // A network agent has requested a connection. Establish the connection.
2360 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2361 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2362 } else {
2363 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002364 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002365 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002367 synchronized (mNetworkForNetId) {
2368 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002369 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002370 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002371 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002372 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002374 }
2375 }
2376 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002377
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378 private void handleAsyncChannelDisconnected(Message msg) {
2379 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2380 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002382 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002383 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002384 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002385 // TODO - if we move the logic to the network agent (have them disconnect
2386 // because they lost all their requests or because their score isn't good)
2387 // then they would disconnect organically, report their new state and then
2388 // disconnect the channel.
2389 if (nai.networkInfo.isConnected()) {
2390 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2391 null, null);
2392 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002393 final boolean wasDefault = isDefaultNetwork(nai);
2394 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002395 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002396 // Log default network disconnection before required book-keeping.
2397 // Let rematchAllNetworksAndRequests() below record a new default network event
2398 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2399 // whose timestamps tell how long it takes to recover a default network.
2400 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002401 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002402 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002403 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2404 // by other networks that are already connected. Perhaps that can be done by
2405 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2406 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002407 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002408 mKeepaliveTracker.handleStopAllKeepalives(nai,
2409 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002410 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002411 mNetworkAgentInfos.remove(msg.replyTo);
2412 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002413 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002414 // Remove the NetworkAgent, but don't mark the netId as
2415 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002416 mNetworkForNetId.remove(nai.network.netId);
2417 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002418 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002419 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2420 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2422 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2423 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 sendUpdatedScoreToFactories(request, 0);
2425 }
2426 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002427 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002428 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002429 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002430 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002431 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002433 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002434 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002435 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002436 if (nai.created) {
2437 // Tell netd to clean up the configuration for this network
2438 // (routing rules, DNS, etc).
2439 // This may be slow as it requires a lot of netd shelling out to ip and
2440 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2441 // after we've rematched networks with requests which should make a potential
2442 // fallback network the default or requested a new network from the
2443 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2444 // long time.
2445 try {
2446 mNetd.removeNetwork(nai.network.netId);
2447 } catch (Exception e) {
2448 loge("Exception removing network: " + e);
2449 }
2450 }
2451 synchronized (mNetworkForNetId) {
2452 mNetIdInUse.delete(nai.network.netId);
2453 }
2454 } else {
2455 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2456 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002457 }
2458 }
2459
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 // If this method proves to be too slow then we can maintain a separate
2461 // pendingIntent => NetworkRequestInfo map.
2462 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2463 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2464 Intent intent = pendingIntent.getIntent();
2465 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2466 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2467 if (existingPendingIntent != null &&
2468 existingPendingIntent.getIntent().filterEquals(intent)) {
2469 return entry.getValue();
2470 }
2471 }
2472 return null;
2473 }
2474
2475 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2476 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2477
2478 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2479 if (existingRequest != null) { // remove the existing request.
2480 if (DBG) log("Replacing " + existingRequest.request + " with "
2481 + nri.request + " because their intents matched.");
2482 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2483 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002484 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002485 }
2486
Erik Klineda4bfa82015-04-30 12:58:40 +09002487 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002488 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002489 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002490 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002491 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002492 if (nri.request.networkCapabilities.hasSignalStrength() &&
2493 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2494 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002495 }
2496 }
2497 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002498 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002499 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002500 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 }
2502 }
2503
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002504 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2505 int callingUid) {
2506 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2507 if (nri != null) {
2508 handleReleaseNetworkRequest(nri.request, callingUid);
2509 }
2510 }
2511
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002512 // Determines whether the network is the best (or could become the best, if it validated), for
2513 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2514 // on the value of reason:
2515 //
2516 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2517 // then it should be torn down.
2518 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2519 // then it should be lingered.
2520 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2521 final int numRequests;
2522 switch (reason) {
2523 case TEARDOWN:
2524 numRequests = nai.numRequestNetworkRequests();
2525 break;
2526 case LINGER:
2527 numRequests = nai.numForegroundNetworkRequests();
2528 break;
2529 default:
2530 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2531 return true;
2532 }
2533
2534 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002535 return false;
2536 }
Paul Jensene0988542015-06-25 15:30:08 -04002537 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002538 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2539 // Background requests don't affect lingering.
2540 continue;
2541 }
2542
Paul Jensene0988542015-06-25 15:30:08 -04002543 // If this Network is already the highest scoring Network for a request, or if
2544 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002545 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002546 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002547 // Note that this catches two important cases:
2548 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2549 // is currently satisfying the request. This is desirable when
2550 // cellular ends up validating but WiFi does not.
2551 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002552 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002553 // WiFi ends up validating and out scoring cellular.
2554 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2555 nai.getCurrentScoreAsValidated())) {
2556 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002557 }
2558 }
Paul Jensene0988542015-06-25 15:30:08 -04002559 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002560 }
2561
Erik Klineacdd6392016-07-07 16:50:58 +09002562 private NetworkRequestInfo getNriForAppRequest(
2563 NetworkRequest request, int callingUid, String requestedOperation) {
2564 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2565
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002567 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002568 log(String.format("UID %d attempted to %s for unowned request %s",
2569 callingUid, requestedOperation, nri));
2570 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002571 }
Erik Klineacdd6392016-07-07 16:50:58 +09002572 }
2573
2574 return nri;
2575 }
2576
2577 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2578 String description, int callbackType) {
2579 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2580 if (nri == null) return;
2581
2582 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2583 // The network that is satisfying this request may have changed since
2584 // the application requested the update.
2585 //
2586 // - If the request is no longer satisfied, don't send any updates.
2587 // - If the request is satisfied by a different network, it is the
2588 // caller's responsibility to check that the Network object in the
2589 // callback matches the network that was returned in the last
2590 // onAvailable() callback for this request.
2591 if (nai == null) return;
2592 callCallbackForRequest(nri, nai, callbackType, 0);
2593 }
2594
2595 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2596 handleRequestCallbackUpdate(request, callingUid,
2597 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2598 }
2599
2600 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2601 handleRequestCallbackUpdate(request, callingUid,
2602 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2603 }
2604
Erik Kline3841a482015-11-25 12:49:38 +09002605 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2606 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2607 nri.request.requestId) == null) {
2608 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2609 }
2610 }
2611
Erik Klineacdd6392016-07-07 16:50:58 +09002612 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2613 final NetworkRequestInfo nri = getNriForAppRequest(
2614 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002615 if (nri != null) {
2616 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2617 }
2618 }
Erik Klineacdd6392016-07-07 16:50:58 +09002619
Erik Kline3841a482015-11-25 12:49:38 +09002620 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2621 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2622 if (VDBG || (DBG && nri.request.isRequest())) {
2623 log("releasing " + nri.request + " (" + logCallbackType + ")");
2624 }
Erik Klineacdd6392016-07-07 16:50:58 +09002625 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002626 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002627 synchronized (mUidToNetworkRequestCount) {
2628 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2629 if (requests < 1) {
2630 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2631 nri.mUid);
2632 } else if (requests == 1) {
2633 mUidToNetworkRequestCount.removeAt(
2634 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2635 } else {
2636 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2637 }
2638 }
2639 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2640 if (nri.request.isRequest()) {
2641 boolean wasKept = false;
2642 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2643 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002644 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002645 nai.removeRequest(nri.request.requestId);
2646 if (VDBG) {
2647 log(" Removing from current network " + nai.name() +
2648 ", leaving " + nai.numNetworkRequests() + " requests.");
2649 }
2650 // If there are still lingered requests on this network, don't tear it down,
2651 // but resume lingering instead.
2652 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002653 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002654 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2655 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002656 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002657 wasKept = true;
2658 }
2659 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002660 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2661 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002662 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002663 }
Erik Klineacdd6392016-07-07 16:50:58 +09002664 }
2665
2666 // TODO: remove this code once we know that the Slog.wtf is never hit.
2667 //
2668 // Find all networks that are satisfying this request and remove the request
2669 // from their request lists.
2670 // TODO - it's my understanding that for a request there is only a single
2671 // network satisfying it, so this loop is wasteful
2672 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2673 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2674 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2675 otherNai.name() + ", but mNetworkAgentInfos says " +
2676 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002677 }
2678 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002679
Erik Klineacdd6392016-07-07 16:50:58 +09002680 // Maintain the illusion. When this request arrived, we might have pretended
2681 // that a network connected to serve it, even though the network was already
2682 // connected. Now that this request has gone away, we might have to pretend
2683 // that the network disconnected. LegacyTypeTracker will generate that
2684 // phantom disconnect for this type.
2685 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2686 boolean doRemove = true;
2687 if (wasKept) {
2688 // check if any of the remaining requests for this network are for the
2689 // same legacy type - if so, don't remove the nai
2690 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2691 NetworkRequest otherRequest = nai.requestAt(i);
2692 if (otherRequest.legacyType == nri.request.legacyType &&
2693 otherRequest.isRequest()) {
2694 if (DBG) log(" still have other legacy request - leaving");
2695 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002696 }
2697 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002698 }
2699
Erik Klineacdd6392016-07-07 16:50:58 +09002700 if (doRemove) {
2701 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002702 }
2703 }
Erik Klineacdd6392016-07-07 16:50:58 +09002704
2705 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2706 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2707 nri.request);
2708 }
2709 } else {
2710 // listens don't have a singular affectedNetwork. Check all networks to see
2711 // if this listen request applies and remove it.
2712 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2713 nai.removeRequest(nri.request.requestId);
2714 if (nri.request.networkCapabilities.hasSignalStrength() &&
2715 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2716 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2717 }
2718 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002719 }
Erik Kline3841a482015-11-25 12:49:38 +09002720 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002721 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002722
Lorenzo Colitti18660282016-07-04 12:55:44 +09002723 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2725 enforceConnectivityInternalPermission();
2726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2727 accept ? 1 : 0, always ? 1: 0, network));
2728 }
2729
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002730 @Override
2731 public void setAvoidUnvalidated(Network network) {
2732 enforceConnectivityInternalPermission();
2733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2734 }
2735
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002736 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2737 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2738 " accept=" + accept + " always=" + always);
2739
2740 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2741 if (nai == null) {
2742 // Nothing to do.
2743 return;
2744 }
2745
2746 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002747 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002748 return;
2749 }
2750
2751 if (!nai.networkMisc.explicitlySelected) {
2752 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2753 }
2754
2755 if (accept != nai.networkMisc.acceptUnvalidated) {
2756 int oldScore = nai.getCurrentScore();
2757 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002758 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002759 sendUpdatedScoreToFactories(nai);
2760 }
2761
2762 if (always) {
2763 nai.asyncChannel.sendMessage(
2764 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2765 }
2766
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002767 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002768 // Tell the NetworkAgent to not automatically reconnect to the network.
2769 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2770 // Teardown the nework.
2771 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002772 }
2773
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002774 }
2775
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002776 private void handleSetAvoidUnvalidated(Network network) {
2777 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2778 if (nai == null || nai.lastValidated) {
2779 // Nothing to do. The network either disconnected or revalidated.
2780 return;
2781 }
2782 if (!nai.avoidUnvalidated) {
2783 int oldScore = nai.getCurrentScore();
2784 nai.avoidUnvalidated = true;
2785 rematchAllNetworksAndRequests(nai, oldScore);
2786 sendUpdatedScoreToFactories(nai);
2787 }
2788 }
2789
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002790 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002791 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002792 mHandler.sendMessageDelayed(
2793 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2794 PROMPT_UNVALIDATED_DELAY_MS);
2795 }
2796
Hugo Benichic8e9e122016-09-14 23:23:08 +00002797 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002798 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002799 }
2800
Erik Kline065ab6e2016-10-02 18:02:14 +09002801 private void rematchForAvoidBadWifiUpdate() {
2802 rematchAllNetworksAndRequests(null, 0);
2803 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2804 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2805 sendUpdatedScoreToFactories(nai);
2806 }
2807 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002808 }
2809
Erik Kline065ab6e2016-10-02 18:02:14 +09002810 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002811 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002812 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002813 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002814 if (!configRestrict) {
2815 pw.println("Bad Wi-Fi avoidance: unrestricted");
2816 return;
2817 }
2818
2819 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2820 pw.increaseIndent();
2821 pw.println("Config restrict: " + configRestrict);
2822
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002823 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002824 String description;
2825 // Can't use a switch statement because strings are legal case labels, but null is not.
2826 if ("0".equals(value)) {
2827 description = "get stuck";
2828 } else if (value == null) {
2829 description = "prompt";
2830 } else if ("1".equals(value)) {
2831 description = "avoid";
2832 } else {
2833 description = value + " (?)";
2834 }
2835 pw.println("User setting: " + description);
2836 pw.println("Network overrides:");
2837 pw.increaseIndent();
2838 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2839 if (nai.avoidUnvalidated) {
2840 pw.println(nai.name());
2841 }
2842 }
2843 pw.decreaseIndent();
2844 pw.decreaseIndent();
2845 }
2846
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002847 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2848 final String action;
2849 switch (type) {
2850 case NO_INTERNET:
2851 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2852 break;
2853 case LOST_INTERNET:
2854 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2855 break;
2856 default:
2857 Slog.wtf(TAG, "Unknown notification type " + type);
2858 return;
2859 }
2860
2861 Intent intent = new Intent(action);
2862 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2863 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2864 intent.setClassName("com.android.settings",
2865 "com.android.settings.wifi.WifiNoInternetDialog");
2866
2867 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2868 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2869 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2870 }
2871
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002872 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002873 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002874 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2875
2876 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2877 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002878 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002879 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002880 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2881 return;
2882 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002883 showValidationNotification(nai, NotificationType.NO_INTERNET);
2884 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002885
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002886 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2887 NetworkCapabilities nc = nai.networkCapabilities;
2888 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002889
Erik Kline065ab6e2016-10-02 18:02:14 +09002890 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002891 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002892 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2893 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002894 }
2895
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002896 private class InternalHandler extends Handler {
2897 public InternalHandler(Looper looper) {
2898 super(looper);
2899 }
2900
2901 @Override
2902 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002903 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002904 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002905 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002906 String causedBy = null;
2907 synchronized (ConnectivityService.this) {
2908 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2909 mNetTransitionWakeLock.isHeld()) {
2910 mNetTransitionWakeLock.release();
2911 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002912 } else {
2913 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002914 }
2915 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002916 if (VDBG) {
2917 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2918 log("Failed to find a new network - expiring NetTransition Wakelock");
2919 } else {
2920 log("NetTransition Wakelock (" +
2921 (causedBy == null ? "unknown" : causedBy) +
2922 " cleared because we found a replacement network");
2923 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002924 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002925 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002926 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002927 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002929 break;
2930 }
Jason Monkdecd2952013-10-10 14:02:51 -04002931 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002932 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002933 break;
2934 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002935 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002936 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2937 break;
2938 }
2939 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2940 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002941 break;
2942 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002943 case EVENT_REGISTER_NETWORK_AGENT: {
2944 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2945 break;
2946 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 case EVENT_REGISTER_NETWORK_REQUEST:
2948 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002949 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002950 break;
2951 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002952 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2953 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002954 handleRegisterNetworkRequestWithIntent(msg);
2955 break;
2956 }
Erik Kline3841a482015-11-25 12:49:38 +09002957 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2958 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2959 handleTimedOutNetworkRequest(nri);
2960 break;
2961 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002962 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2963 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2964 break;
2965 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002967 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002968 break;
2969 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002970 case EVENT_SET_ACCEPT_UNVALIDATED: {
2971 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2972 break;
2973 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002974 case EVENT_SET_AVOID_UNVALIDATED: {
2975 handleSetAvoidUnvalidated((Network) msg.obj);
2976 break;
2977 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002978 case EVENT_PROMPT_UNVALIDATED: {
2979 handlePromptUnvalidated((Network) msg.obj);
2980 break;
2981 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002982 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2983 handleMobileDataAlwaysOn();
2984 break;
2985 }
Erik Klineacdd6392016-07-07 16:50:58 +09002986 case EVENT_REQUEST_LINKPROPERTIES:
2987 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2988 break;
2989 case EVENT_REQUEST_NETCAPABILITIES:
2990 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2991 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002992 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2993 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2994 mKeepaliveTracker.handleStartKeepalive(msg);
2995 break;
2996 }
2997 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2998 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2999 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3000 int slot = msg.arg1;
3001 int reason = msg.arg2;
3002 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3003 break;
3004 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003005 case EVENT_SYSTEM_READY: {
3006 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3007 nai.networkMonitor.systemReady = true;
3008 }
3009 break;
3010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 }
3012 }
3013 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003014
3015 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003017 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003018 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003019 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003020 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003021 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003022 } else {
3023 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3024 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003025 }
3026
3027 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003029 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003030 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003031
3032 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003033 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003034 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003035 } else {
3036 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3037 }
3038 }
3039
3040 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003041 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003042 public int getLastTetherError(String iface) {
3043 enforceTetherAccessPermission();
3044
3045 if (isTetheringSupported()) {
3046 return mTethering.getLastTetherError(iface);
3047 } else {
3048 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3049 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003050 }
3051
3052 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003053 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003054 public String[] getTetherableUsbRegexs() {
3055 enforceTetherAccessPermission();
3056 if (isTetheringSupported()) {
3057 return mTethering.getTetherableUsbRegexs();
3058 } else {
3059 return new String[0];
3060 }
3061 }
3062
Lorenzo Colitti18660282016-07-04 12:55:44 +09003063 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003064 public String[] getTetherableWifiRegexs() {
3065 enforceTetherAccessPermission();
3066 if (isTetheringSupported()) {
3067 return mTethering.getTetherableWifiRegexs();
3068 } else {
3069 return new String[0];
3070 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003071 }
3072
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003074 public String[] getTetherableBluetoothRegexs() {
3075 enforceTetherAccessPermission();
3076 if (isTetheringSupported()) {
3077 return mTethering.getTetherableBluetoothRegexs();
3078 } else {
3079 return new String[0];
3080 }
3081 }
3082
Lorenzo Colitti18660282016-07-04 12:55:44 +09003083 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003084 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003085 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003086 if (isTetheringSupported()) {
3087 return mTethering.setUsbTethering(enable);
3088 } else {
3089 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3090 }
3091 }
3092
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003093 // TODO - move iface listing, queries, etc to new module
3094 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003096 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003097 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003098 return mTethering.getTetherableIfaces();
3099 }
3100
Lorenzo Colitti18660282016-07-04 12:55:44 +09003101 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003102 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003103 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003104 return mTethering.getTetheredIfaces();
3105 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003106
Lorenzo Colitti18660282016-07-04 12:55:44 +09003107 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003108 public String[] getTetheringErroredIfaces() {
3109 enforceTetherAccessPermission();
3110 return mTethering.getErroredIfaces();
3111 }
3112
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003114 public String[] getTetheredDhcpRanges() {
3115 enforceConnectivityInternalPermission();
3116 return mTethering.getTetheredDhcpRanges();
3117 }
3118
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003119 // if ro.tether.denied = true we default to no tethering
3120 // gservices could set the secure setting to 1 though to enable it on a build where it
3121 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003122 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003123 public boolean isTetheringSupported() {
3124 enforceTetherAccessPermission();
3125 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003126 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003127 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3128 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003129 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
Erik Klined781fba2017-01-23 13:01:58 +09003130 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003131 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003132
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003133 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003134 public void startTethering(int type, ResultReceiver receiver,
3135 boolean showProvisioningUi) {
3136 ConnectivityManager.enforceTetherChangePermission(mContext);
3137 if (!isTetheringSupported()) {
3138 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3139 return;
3140 }
3141 mTethering.startTethering(type, receiver, showProvisioningUi);
3142 }
3143
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003144 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003145 public void stopTethering(int type) {
3146 ConnectivityManager.enforceTetherChangePermission(mContext);
3147 mTethering.stopTethering(type);
3148 }
3149
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003150 // Called when we lose the default network and have no replacement yet.
3151 // This will automatically be cleared after X seconds or a new default network
3152 // becomes CONNECTED, whichever happens first. The timer is started by the
3153 // first caller and not restarted by subsequent callers.
3154 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003155 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003156 synchronized (this) {
3157 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003158 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003159 mNetTransitionWakeLock.acquire();
3160 mNetTransitionWakeLockCausedBy = forWhom;
3161 }
3162 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003163 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003164 mNetTransitionWakeLockTimeout);
3165 return;
3166 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003167
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003168 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003169 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003170 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003171 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003172 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003173 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003174 }
3175
Lorenzo Colitti18660282016-07-04 12:55:44 +09003176 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003177 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003178 enforceAccessPermission();
3179 enforceInternetPermission();
3180
Paul Jensenbfd17b72015-04-07 12:43:13 -04003181 NetworkAgentInfo nai;
3182 if (network == null) {
3183 nai = getDefaultNetwork();
3184 } else {
3185 nai = getNetworkAgentInfoForNetwork(network);
3186 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003187 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3188 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3189 return;
3190 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003191 // Revalidate if the app report does not match our current validated state.
3192 if (hasConnectivity == nai.lastValidated) return;
3193 final int uid = Binder.getCallingUid();
3194 if (DBG) {
3195 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3196 ") by " + uid);
3197 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003198 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003199 // Validating a network that has not yet connected could result in a call to
3200 // rematchNetworkAndRequests() which is not meant to work on such networks.
3201 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003202
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003203 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003204
3205 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3206 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003207 }
3208
Paul Jensencee9b512015-05-06 07:32:40 -04003209 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003210 // this information is already available as a world read/writable jvm property
3211 // so this API change wouldn't have a benifit. It also breaks the passing
3212 // of proxy info to all the JVMs.
3213 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003214 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003215 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003216 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3217 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003218 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003219 }
3220
Lorenzo Colitti18660282016-07-04 12:55:44 +09003221 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003222 public ProxyInfo getProxyForNetwork(Network network) {
3223 if (network == null) return getDefaultProxy();
3224 final ProxyInfo globalProxy = getGlobalProxy();
3225 if (globalProxy != null) return globalProxy;
3226 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3227 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3228 // caller may not have.
3229 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3230 if (nai == null) return null;
3231 synchronized (nai) {
3232 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3233 if (proxyInfo == null) return null;
3234 return new ProxyInfo(proxyInfo);
3235 }
3236 }
3237
Paul Jensene0bef712014-12-10 15:12:18 -05003238 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3239 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3240 // proxy is null then there is no proxy in place).
3241 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3242 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3243 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3244 proxy = null;
3245 }
3246 return proxy;
3247 }
3248
3249 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3250 // better for determining if a new proxy broadcast is necessary:
3251 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3252 // avoid unnecessary broadcasts.
3253 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3254 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3255 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3256 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3257 // all set.
3258 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3259 a = canonicalizeProxyInfo(a);
3260 b = canonicalizeProxyInfo(b);
3261 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3262 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3263 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3264 }
3265
Jason Monk207900c2014-04-25 15:00:09 -04003266 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003267 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003268
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003269 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003270 if (proxyProperties == mGlobalProxy) return;
3271 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3272 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3273
3274 String host = "";
3275 int port = 0;
3276 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003277 String pacFileUrl = "";
3278 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003279 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003280 if (!proxyProperties.isValid()) {
3281 if (DBG)
3282 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3283 return;
3284 }
Jason Monk207900c2014-04-25 15:00:09 -04003285 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003286 host = mGlobalProxy.getHost();
3287 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003288 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003289 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003290 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003291 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003292 } else {
3293 mGlobalProxy = null;
3294 }
3295 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003296 final long token = Binder.clearCallingIdentity();
3297 try {
3298 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3299 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3300 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3301 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003302 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003303 } finally {
3304 Binder.restoreCallingIdentity(token);
3305 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306
Jason Monkcf0f97a2014-10-02 15:39:38 -04003307 if (mGlobalProxy == null) {
3308 proxyProperties = mDefaultProxy;
3309 }
3310 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003312 }
3313
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003314 private void loadGlobalProxy() {
3315 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003316 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3317 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3318 String exclList = Settings.Global.getString(res,
3319 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003320 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3321 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003322 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003323 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003324 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003325 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003326 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003327 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003328 if (!proxyProperties.isValid()) {
3329 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3330 return;
3331 }
3332
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003333 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003334 mGlobalProxy = proxyProperties;
3335 }
3336 }
3337 }
3338
Jason Monk207900c2014-04-25 15:00:09 -04003339 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003340 // this information is already available as a world read/writable jvm property
3341 // so this API change wouldn't have a benifit. It also breaks the passing
3342 // of proxy info to all the JVMs.
3343 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003344 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003345 return mGlobalProxy;
3346 }
3347 }
3348
Jason Monk207900c2014-04-25 15:00:09 -04003349 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003350 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003351 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003352 proxy = null;
3353 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003354 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003356 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003357 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003358 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3359 return;
3360 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003361
3362 // This call could be coming from the PacManager, containing the port of the local
3363 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3364 // global (to get the correct local port), and send a broadcast.
3365 // TODO: Switch PacManager to have its own message to send back rather than
3366 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003367 if ((mGlobalProxy != null) && (proxy != null)
3368 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003369 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3370 mGlobalProxy = proxy;
3371 sendProxyBroadcast(mGlobalProxy);
3372 return;
3373 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003374 mDefaultProxy = proxy;
3375
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003376 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003377 if (!mDefaultProxyDisabled) {
3378 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003379 }
3380 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 }
3382
Paul Jensene0bef712014-12-10 15:12:18 -05003383 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3384 // This method gets called when any network changes proxy, but the broadcast only ever contains
3385 // the default proxy (even if it hasn't changed).
3386 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3387 // world where an app might be bound to a non-default network.
3388 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3389 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3390 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3391
3392 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3393 sendProxyBroadcast(getDefaultProxy());
3394 }
3395 }
3396
Robert Greenwalt434203a2010-10-11 16:00:27 -07003397 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003398 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3399 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003400 if (!TextUtils.isEmpty(proxy)) {
3401 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003402 if (data.length == 0) {
3403 return;
3404 }
3405
Robert Greenwalt434203a2010-10-11 16:00:27 -07003406 String proxyHost = data[0];
3407 int proxyPort = 8080;
3408 if (data.length > 1) {
3409 try {
3410 proxyPort = Integer.parseInt(data[1]);
3411 } catch (NumberFormatException e) {
3412 return;
3413 }
3414 }
Jason Monk207900c2014-04-25 15:00:09 -04003415 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003416 setGlobalProxy(p);
3417 }
3418 }
3419
Jason Monk207900c2014-04-25 15:00:09 -04003420 private void sendProxyBroadcast(ProxyInfo proxy) {
3421 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003422 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003423 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003424 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003425 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3426 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003427 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003428 final long ident = Binder.clearCallingIdentity();
3429 try {
3430 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3431 } finally {
3432 Binder.restoreCallingIdentity(ident);
3433 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003434 }
3435
3436 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003437 final private HashMap<Uri, Integer> mUriEventMap;
3438 final private Context mContext;
3439 final private Handler mHandler;
3440
3441 SettingsObserver(Context context, Handler handler) {
3442 super(null);
3443 mUriEventMap = new HashMap<Uri, Integer>();
3444 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003445 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003446 }
3447
Erik Klineda4bfa82015-04-30 12:58:40 +09003448 void observe(Uri uri, int what) {
3449 mUriEventMap.put(uri, what);
3450 final ContentResolver resolver = mContext.getContentResolver();
3451 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003452 }
3453
3454 @Override
3455 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003456 Slog.wtf(TAG, "Should never be reached.");
3457 }
3458
3459 @Override
3460 public void onChange(boolean selfChange, Uri uri) {
3461 final Integer what = mUriEventMap.get(uri);
3462 if (what != null) {
3463 mHandler.obtainMessage(what.intValue()).sendToTarget();
3464 } else {
3465 loge("No matching event to send for URI=" + uri);
3466 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003467 }
3468 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003469
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003470 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003471 Slog.d(TAG, s);
3472 }
3473
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003474 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003475 Slog.e(TAG, s);
3476 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003477
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003478 private static <T> T checkNotNull(T value, String message) {
3479 if (value == null) {
3480 throw new NullPointerException(message);
3481 }
3482 return value;
3483 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003484
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003485 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003486 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003487 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3488 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3489 *
3490 * @param oldPackage Package name of the application which currently controls VPN, which will
3491 * be replaced. If there is no such application, this should should either be
3492 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3493 * @param newPackage Package name of the application which should gain control of VPN, or
3494 * {@code null} to disable.
3495 * @param userId User for whom to prepare the new VPN.
3496 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003497 * @hide
3498 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003499 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003500 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3501 int userId) {
3502 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003503 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003504
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003505 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003506 Vpn vpn = mVpns.get(userId);
3507 if (vpn != null) {
3508 return vpn.prepare(oldPackage, newPackage);
3509 } else {
3510 return false;
3511 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003512 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003513 }
3514
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003515 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003516 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3517 * This method is used by system-privileged apps.
3518 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3519 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3520 *
3521 * @param packageName The package for which authorization state should change.
3522 * @param userId User for whom {@code packageName} is installed.
3523 * @param authorized {@code true} if this app should be able to start a VPN connection without
3524 * explicit user approval, {@code false} if not.
3525 *
Jeff Davidson05542602014-08-11 14:07:27 -07003526 * @hide
3527 */
3528 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003529 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3530 enforceCrossUserPermission(userId);
3531
Jeff Davidson05542602014-08-11 14:07:27 -07003532 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003533 Vpn vpn = mVpns.get(userId);
3534 if (vpn != null) {
3535 vpn.setPackageAuthorization(packageName, authorized);
3536 }
Jeff Davidson05542602014-08-11 14:07:27 -07003537 }
3538 }
3539
3540 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003541 * Configure a TUN interface and return its file descriptor. Parameters
3542 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003543 * and not available in ConnectivityManager. Permissions are checked in
3544 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003545 * @hide
3546 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003547 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003548 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003549 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003550 int user = UserHandle.getUserId(Binder.getCallingUid());
3551 synchronized(mVpns) {
3552 return mVpns.get(user).establish(config);
3553 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003554 }
3555
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003556 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003557 * Start legacy VPN, controlling native daemons as needed. Creates a
3558 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003559 */
3560 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003561 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003562 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003563 final LinkProperties egress = getActiveLinkProperties();
3564 if (egress == null) {
3565 throw new IllegalStateException("Missing active network connection");
3566 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003567 int user = UserHandle.getUserId(Binder.getCallingUid());
3568 synchronized(mVpns) {
3569 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3570 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003571 }
3572
3573 /**
3574 * Return the information of the ongoing legacy VPN. This method is used
3575 * by VpnSettings and not available in ConnectivityManager. Permissions
3576 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003577 */
3578 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003579 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3580 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003581
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003582 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003583 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003585 }
3586
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003587 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003588 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3589 * and not available in ConnectivityManager.
3590 */
3591 @Override
3592 public VpnInfo[] getAllVpnInfo() {
3593 enforceConnectivityInternalPermission();
3594 if (mLockdownEnabled) {
3595 return new VpnInfo[0];
3596 }
3597
3598 synchronized(mVpns) {
3599 List<VpnInfo> infoList = new ArrayList<>();
3600 for (int i = 0; i < mVpns.size(); i++) {
3601 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3602 if (info != null) {
3603 infoList.add(info);
3604 }
3605 }
3606 return infoList.toArray(new VpnInfo[infoList.size()]);
3607 }
3608 }
3609
3610 /**
3611 * @return VPN information for accounting, or null if we can't retrieve all required
3612 * information, e.g primary underlying iface.
3613 */
3614 @Nullable
3615 private VpnInfo createVpnInfo(Vpn vpn) {
3616 VpnInfo info = vpn.getVpnInfo();
3617 if (info == null) {
3618 return null;
3619 }
3620 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3621 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3622 // the underlyingNetworks list.
3623 if (underlyingNetworks == null) {
3624 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3625 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3626 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3627 }
3628 } else if (underlyingNetworks.length > 0) {
3629 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3630 if (linkProperties != null) {
3631 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3632 }
3633 }
3634 return info.primaryUnderlyingIface == null ? null : info;
3635 }
3636
3637 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003638 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3639 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003640 * Permissions are checked in Vpn class.
3641 * @hide
3642 */
3643 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003644 public VpnConfig getVpnConfig(int userId) {
3645 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003646 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003647 Vpn vpn = mVpns.get(userId);
3648 if (vpn != null) {
3649 return vpn.getVpnConfig();
3650 } else {
3651 return null;
3652 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003653 }
3654 }
3655
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003656 @Override
3657 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003658 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3659 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3660 return false;
3661 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003662
3663 // Tear down existing lockdown if profile was removed
3664 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3665 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003666 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3667 if (profileTag == null) {
3668 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3669 return false;
3670 }
3671 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003672 final VpnProfile profile = VpnProfile.decode(
3673 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003674 if (profile == null) {
3675 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3676 setLockdownTracker(null);
3677 return true;
3678 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003679 int user = UserHandle.getUserId(Binder.getCallingUid());
3680 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003681 Vpn vpn = mVpns.get(user);
3682 if (vpn == null) {
3683 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3684 return false;
3685 }
3686 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003687 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003688 } else {
3689 setLockdownTracker(null);
3690 }
3691
3692 return true;
3693 }
3694
3695 /**
3696 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3697 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3698 */
3699 private void setLockdownTracker(LockdownVpnTracker tracker) {
3700 // Shutdown any existing tracker
3701 final LockdownVpnTracker existing = mLockdownTracker;
3702 mLockdownTracker = null;
3703 if (existing != null) {
3704 existing.shutdown();
3705 }
3706
3707 try {
3708 if (tracker != null) {
3709 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003710 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003711 mLockdownTracker = tracker;
3712 mLockdownTracker.init();
3713 } else {
3714 mNetd.setFirewallEnabled(false);
3715 }
3716 } catch (RemoteException e) {
3717 // ignored; NMS lives inside system_server
3718 }
3719 }
3720
3721 private void throwIfLockdownEnabled() {
3722 if (mLockdownEnabled) {
3723 throw new IllegalStateException("Unavailable in lockdown mode");
3724 }
3725 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003726
Robin Lee244ce8e2016-01-05 18:03:46 +00003727 /**
Robin Lee17e61832016-05-09 13:46:28 +01003728 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3729 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003730 *
Robin Lee17e61832016-05-09 13:46:28 +01003731 * @return {@code true} if the service was started, the service was already connected, or there
3732 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003733 */
Robin Lee17e61832016-05-09 13:46:28 +01003734 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003735 synchronized (mVpns) {
3736 Vpn vpn = mVpns.get(userId);
3737 if (vpn == null) {
3738 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3739 // exists already.
3740 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3741 return false;
3742 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003743
Robin Lee812800c2016-05-13 15:38:08 +01003744 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003745 }
3746 }
3747
3748 @Override
Robin Leedc679712016-05-03 13:23:03 +01003749 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003750 enforceConnectivityInternalPermission();
3751 enforceCrossUserPermission(userId);
3752
3753 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3754 if (LockdownVpnTracker.isEnabled()) {
3755 return false;
3756 }
3757
Robin Lee244ce8e2016-01-05 18:03:46 +00003758 synchronized (mVpns) {
3759 Vpn vpn = mVpns.get(userId);
3760 if (vpn == null) {
3761 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3762 return false;
3763 }
Robin Lee17e61832016-05-09 13:46:28 +01003764 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003765 return false;
3766 }
Robin Lee17e61832016-05-09 13:46:28 +01003767 if (!startAlwaysOnVpn(userId)) {
3768 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003769 return false;
3770 }
Robin Lee17e61832016-05-09 13:46:28 +01003771
Robin Lee812800c2016-05-13 15:38:08 +01003772 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003773 }
3774 return true;
3775 }
3776
3777 @Override
3778 public String getAlwaysOnVpnPackage(int userId) {
3779 enforceConnectivityInternalPermission();
3780 enforceCrossUserPermission(userId);
3781
3782 synchronized (mVpns) {
3783 Vpn vpn = mVpns.get(userId);
3784 if (vpn == null) {
3785 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3786 return null;
3787 }
3788 return vpn.getAlwaysOnPackage();
3789 }
3790 }
3791
Wink Savilleab9321d2013-06-29 21:10:57 -07003792 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003793 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003794 // TODO: Remove? Any reason to trigger a provisioning check?
3795 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003796 }
3797
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003798 /** Location to an updatable file listing carrier provisioning urls.
3799 * An example:
3800 *
3801 * <?xml version="1.0" encoding="utf-8"?>
3802 * <provisioningUrls>
3803 * <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 -07003804 * </provisioningUrls>
3805 */
3806 private static final String PROVISIONING_URL_PATH =
3807 "/data/misc/radio/provisioning_urls.xml";
3808 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003809
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003810 /** XML tag for root element. */
3811 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3812 /** XML tag for individual url */
3813 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003814 /** XML attribute for mcc */
3815 private static final String ATTR_MCC = "mcc";
3816 /** XML attribute for mnc */
3817 private static final String ATTR_MNC = "mnc";
3818
Paul Jensen434dde82015-06-11 09:43:30 -04003819 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003820 FileReader fileReader = null;
3821 XmlPullParser parser = null;
3822 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003823
3824 try {
3825 fileReader = new FileReader(mProvisioningUrlFile);
3826 parser = Xml.newPullParser();
3827 parser.setInput(fileReader);
3828 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3829
3830 while (true) {
3831 XmlUtils.nextElement(parser);
3832
3833 String element = parser.getName();
3834 if (element == null) break;
3835
Paul Jensen434dde82015-06-11 09:43:30 -04003836 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003837 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3838 try {
3839 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3840 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3841 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3842 parser.next();
3843 if (parser.getEventType() == XmlPullParser.TEXT) {
3844 return parser.getText();
3845 }
3846 }
3847 }
3848 } catch (NumberFormatException e) {
3849 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3850 }
3851 }
3852 }
3853 return null;
3854 } catch (FileNotFoundException e) {
3855 loge("Carrier Provisioning Urls file not found");
3856 } catch (XmlPullParserException e) {
3857 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3858 } catch (IOException e) {
3859 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3860 } finally {
3861 if (fileReader != null) {
3862 try {
3863 fileReader.close();
3864 } catch (IOException e) {}
3865 }
3866 }
3867 return null;
3868 }
3869
Wink Saville42d4f082013-07-20 20:31:59 -07003870 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003871 public String getMobileProvisioningUrl() {
3872 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003873 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003874 if (TextUtils.isEmpty(url)) {
3875 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003876 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003877 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003878 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003879 }
Wink Saville8cf35602013-07-10 23:00:07 -07003880 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003881 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003882 String phoneNumber = mTelephonyManager.getLine1Number();
3883 if (TextUtils.isEmpty(phoneNumber)) {
3884 phoneNumber = "0000000000";
3885 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003886 url = String.format(url,
3887 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3888 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003889 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003890 }
3891
Wink Savilleab9321d2013-06-29 21:10:57 -07003892 return url;
3893 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003894
Wink Saville948282b2013-08-29 08:55:16 -07003895 @Override
3896 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003897 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003898 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003899 final long ident = Binder.clearCallingIdentity();
3900 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003901 // Concatenate the range of types onto the range of NetIDs.
3902 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3903 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003904 } finally {
3905 Binder.restoreCallingIdentity(ident);
3906 }
Wink Saville948282b2013-08-29 08:55:16 -07003907 }
Wink Saville7788c612013-08-29 14:57:08 -07003908
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003909 @Override
3910 public void setAirplaneMode(boolean enable) {
3911 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003912 final long ident = Binder.clearCallingIdentity();
3913 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003914 final ContentResolver cr = mContext.getContentResolver();
3915 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3916 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3917 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003918 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003919 } finally {
3920 Binder.restoreCallingIdentity(ident);
3921 }
3922 }
3923
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003924 private void onUserStart(int userId) {
3925 synchronized(mVpns) {
3926 Vpn userVpn = mVpns.get(userId);
3927 if (userVpn != null) {
3928 loge("Starting user already has a VPN");
3929 return;
3930 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003931 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003932 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003933
3934 final ContentResolver cr = mContext.getContentResolver();
3935 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3936 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3937 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3938 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3939 if (alwaysOnPackage != null) {
3940 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3941 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003942 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003943 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3944 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003945 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003946 }
3947
3948 private void onUserStop(int userId) {
3949 synchronized(mVpns) {
3950 Vpn userVpn = mVpns.get(userId);
3951 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003952 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 return;
3954 }
Robin Lee17e61832016-05-09 13:46:28 +01003955 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003956 mVpns.delete(userId);
3957 }
3958 }
3959
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003960 private void onUserAdded(int userId) {
3961 synchronized(mVpns) {
3962 final int vpnsSize = mVpns.size();
3963 for (int i = 0; i < vpnsSize; i++) {
3964 Vpn vpn = mVpns.valueAt(i);
3965 vpn.onUserAdded(userId);
3966 }
3967 }
3968 }
3969
3970 private void onUserRemoved(int userId) {
3971 synchronized(mVpns) {
3972 final int vpnsSize = mVpns.size();
3973 for (int i = 0; i < vpnsSize; i++) {
3974 Vpn vpn = mVpns.valueAt(i);
3975 vpn.onUserRemoved(userId);
3976 }
3977 }
3978 }
3979
Robin Lee89e7a692016-02-29 14:38:17 +00003980 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003981 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3982 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3983 updateLockdownVpn();
3984 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003985 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003986 }
3987 }
3988
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003989 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3990 @Override
3991 public void onReceive(Context context, Intent intent) {
3992 final String action = intent.getAction();
3993 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3994 if (userId == UserHandle.USER_NULL) return;
3995
Robin Lee323f29d2016-05-04 16:38:06 +01003996 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003997 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003998 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003999 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004000 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4001 onUserAdded(userId);
4002 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4003 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004004 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4005 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004006 }
4007 }
4008 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004009
Robin Lee95204e02017-01-27 11:59:22 +00004010 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4011 @Override
4012 public void onReceive(Context context, Intent intent) {
4013 // Try creating lockdown tracker, since user present usually means
4014 // unlocked keystore.
4015 updateLockdownVpn();
4016 mContext.unregisterReceiver(this);
4017 }
4018 };
4019
Robert Greenwalta67be032014-05-16 15:49:14 -07004020 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4021 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4023 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004024
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004025 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4026 // Map from UID to number of NetworkRequests that UID has filed.
4027 @GuardedBy("mUidToNetworkRequestCount")
4028 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4029
Robert Greenwalta67be032014-05-16 15:49:14 -07004030 private static class NetworkFactoryInfo {
4031 public final String name;
4032 public final Messenger messenger;
4033 public final AsyncChannel asyncChannel;
4034
4035 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4036 this.name = name;
4037 this.messenger = messenger;
4038 this.asyncChannel = asyncChannel;
4039 }
4040 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004042 private void ensureNetworkRequestHasType(NetworkRequest request) {
4043 if (request.type == NetworkRequest.Type.NONE) {
4044 throw new IllegalArgumentException(
4045 "All NetworkRequests in ConnectivityService must have a type");
4046 }
4047 }
4048
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004049 /**
4050 * Tracks info about the requester.
4051 * Also used to notice when the calling process dies so we can self-expire
4052 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004053 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004054 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004056 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004057 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 final int mPid;
4059 final int mUid;
4060 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004062 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004063 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004064 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004065 mPendingIntent = pi;
4066 messenger = null;
4067 mBinder = null;
4068 mPid = getCallingPid();
4069 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004070 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004071 }
4072
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004073 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 super();
4075 messenger = m;
4076 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004077 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 mBinder = binder;
4079 mPid = getCallingPid();
4080 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004081 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004082 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083
4084 try {
4085 mBinder.linkToDeath(this, 0);
4086 } catch (RemoteException e) {
4087 binderDied();
4088 }
4089 }
4090
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004091 private void enforceRequestCountLimit() {
4092 synchronized (mUidToNetworkRequestCount) {
4093 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4094 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4095 throw new IllegalArgumentException("Too many NetworkRequests filed");
4096 }
4097 mUidToNetworkRequestCount.put(mUid, networkRequests);
4098 }
4099 }
4100
Robert Greenwalt9258c642014-03-26 16:47:06 -07004101 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004102 if (mBinder != null) {
4103 mBinder.unlinkToDeath(this, 0);
4104 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 }
4106
4107 public void binderDied() {
4108 log("ConnectivityService NetworkRequestInfo binderDied(" +
4109 request + ", " + mBinder + ")");
4110 releaseNetworkRequest(request);
4111 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004112
4113 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004114 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004116 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 }
4118
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004119 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4120 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4121 if (badCapability != null) {
4122 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004123 }
4124 }
4125
Erik Kline9d598e12015-07-13 16:37:51 +09004126 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004127 final SortedSet<Integer> thresholds = new TreeSet();
4128 synchronized (nai) {
4129 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4130 if (nri.request.networkCapabilities.hasSignalStrength() &&
4131 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4132 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4133 }
4134 }
4135 }
Erik Kline9d598e12015-07-13 16:37:51 +09004136 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004137 }
4138
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004139 private void updateSignalStrengthThresholds(
4140 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4141 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004142 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004143 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4144
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004145 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004146 String detail;
4147 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4148 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4149 } else {
4150 detail = reason;
4151 }
4152 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4153 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4154 }
4155
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004156 nai.asyncChannel.sendMessage(
4157 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004158 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004159 }
4160
Robert Greenwalt9258c642014-03-26 16:47:06 -07004161 @Override
4162 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004163 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004164 final NetworkRequest.Type type = (networkCapabilities == null)
4165 ? NetworkRequest.Type.TRACK_DEFAULT
4166 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004167 // If the requested networkCapabilities is null, take them instead from
4168 // the default network request. This allows callers to keep track of
4169 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004170 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004171 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4172 enforceAccessPermission();
4173 } else {
4174 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4175 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004176 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4177 // of the app when the request is filed, but we never change the request if the app
4178 // changes network state. http://b/29964605
4179 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004180 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004181 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004182
Etan Cohenba07c8c2017-02-05 10:42:27 -08004183 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184 throw new IllegalArgumentException("Bad timeout specified");
4185 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004186
Etan Cohenddb9ef02015-11-18 10:56:15 -08004187 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4188 .equals(networkCapabilities.getNetworkSpecifier())) {
4189 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4190 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4191 }
4192
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004193 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004194 nextNetworkRequestId(), type);
4195 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004196 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197
4198 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004199 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004200 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004201 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202 }
4203 return networkRequest;
4204 }
4205
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004207 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004208 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 } else {
4210 enforceChangePermission();
4211 }
4212 }
4213
fenglub15e72b2015-03-20 11:29:56 -07004214 @Override
fengludb571472015-04-21 17:12:05 -07004215 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004216 enforceAccessPermission();
4217 NetworkAgentInfo nai = null;
4218 if (network == null) {
4219 return false;
4220 }
4221 synchronized (mNetworkForNetId) {
4222 nai = mNetworkForNetId.get(network.netId);
4223 }
4224 if (nai != null) {
4225 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4226 return true;
4227 }
4228 return false;
4229 }
4230
Felipe Lemeee27cab2016-06-20 16:36:29 -07004231 private boolean isSystem(int uid) {
4232 return uid < Process.FIRST_APPLICATION_UID;
4233 }
fenglub15e72b2015-03-20 11:29:56 -07004234
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004235 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004236 final int uid = Binder.getCallingUid();
4237 if (isSystem(uid)) {
4238 return;
4239 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004240 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004241 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004242 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004243 synchronized(mRulesLock) {
4244 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4245 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004246 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4247 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004248 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004249 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004250 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004251 }
4252 }
4253 }
4254
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255 @Override
4256 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4257 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004258 checkNotNull(operation, "PendingIntent cannot be null.");
4259 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4260 enforceNetworkRequestPermissions(networkCapabilities);
4261 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004262 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004263
4264 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004265 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4266 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004267 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004268 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4269 nri));
4270 return networkRequest;
4271 }
4272
Jeremy Joslin79294842014-12-03 17:15:28 -08004273 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4274 mHandler.sendMessageDelayed(
4275 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4276 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4277 }
4278
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004279 @Override
4280 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004281 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4283 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004284 }
4285
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004286 // In order to implement the compatibility measure for pre-M apps that call
4287 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4288 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4289 // This ensures it has permission to do so.
4290 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4291 if (nc == null) {
4292 return false;
4293 }
4294 int[] transportTypes = nc.getTransportTypes();
4295 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4296 return false;
4297 }
4298 try {
4299 mContext.enforceCallingOrSelfPermission(
4300 android.Manifest.permission.ACCESS_WIFI_STATE,
4301 "ConnectivityService");
4302 } catch (SecurityException e) {
4303 return false;
4304 }
4305 return true;
4306 }
4307
Robert Greenwalt9258c642014-03-26 16:47:06 -07004308 @Override
4309 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4310 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004311 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4312 enforceAccessPermission();
4313 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004315 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4316 if (!ConnectivityManager.checkChangePermission(mContext)) {
4317 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4318 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4319 // onLost and onAvailable callbacks when networks move in and out of the background.
4320 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4321 // can't request networks.
4322 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4323 }
4324
4325 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004326 NetworkRequest.Type.LISTEN);
4327 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004328 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329
4330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4331 return networkRequest;
4332 }
4333
4334 @Override
4335 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4336 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004337 checkNotNull(operation, "PendingIntent cannot be null.");
4338 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4339 enforceAccessPermission();
4340 }
4341
Erik Kline7523eb32015-07-09 18:24:03 +09004342 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004343 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4344 NetworkRequest.Type.LISTEN);
4345 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004346 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004347
4348 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004349 }
4350
Erik Klinec75d4fa2017-02-15 19:59:17 +09004351 // TODO: Delete once callers are updated.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004353 public void requestLinkProperties(NetworkRequest networkRequest) {
4354 ensureNetworkRequestHasType(networkRequest);
4355 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4356 mHandler.sendMessage(mHandler.obtainMessage(
4357 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4358 }
4359
Erik Klinec75d4fa2017-02-15 19:59:17 +09004360 // TODO: Delete once callers are updated.
Erik Klineacdd6392016-07-07 16:50:58 +09004361 @Override
4362 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4363 ensureNetworkRequestHasType(networkRequest);
4364 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4365 mHandler.sendMessage(mHandler.obtainMessage(
4366 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4367 }
4368
4369 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004370 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004371 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004372 mHandler.sendMessage(mHandler.obtainMessage(
4373 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004374 }
4375
4376 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004377 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004378 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004379 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4380 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004381 }
4382
Robert Greenwalta67be032014-05-16 15:49:14 -07004383 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004384 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004385 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4386 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4387 }
4388
4389 @Override
4390 public void unregisterNetworkFactory(Messenger messenger) {
4391 enforceConnectivityInternalPermission();
4392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4393 }
4394
4395 private void handleUnregisterNetworkFactory(Messenger messenger) {
4396 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4397 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004398 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004399 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004400 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004401 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004402 }
4403
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 /**
4405 * NetworkAgentInfo supporting a request by requestId.
4406 * These have already been vetted (their Capabilities satisfy the request)
4407 * and the are the highest scored network available.
4408 * the are keyed off the Requests requestId.
4409 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004410 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4412 new SparseArray<NetworkAgentInfo>();
4413
Paul Jensen31a94f42015-02-13 14:18:39 -05004414 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4415 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004416 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4417 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004418 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4419 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4420 // there may not be a strict 1:1 correlation between the two.
4421 @GuardedBy("mNetworkForNetId")
4422 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004423
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 // NetworkAgentInfo keyed off its connecting messenger
4425 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004426 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004427 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4428 new HashMap<Messenger, NetworkAgentInfo>();
4429
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004430 @GuardedBy("mBlockedAppUids")
4431 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4432
Paul Jensen2c311d62014-11-17 12:34:51 -05004433 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004434 private final NetworkRequest mDefaultRequest;
4435
Erik Klineda4bfa82015-04-30 12:58:40 +09004436 // Request used to optionally keep mobile data active even when higher
4437 // priority networks like Wi-Fi are active.
4438 private final NetworkRequest mDefaultMobileDataRequest;
4439
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004440 private NetworkAgentInfo getDefaultNetwork() {
4441 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4442 }
4443
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004444 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004445 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004446 }
4447
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004448 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4449 return nri.request.requestId == mDefaultRequest.requestId;
4450 }
4451
Paul Jensen31a94f42015-02-13 14:18:39 -05004452 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004454 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004455 enforceConnectivityInternalPermission();
4456
Paul Jensen2c311d62014-11-17 12:34:51 -05004457 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4458 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004459 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004460 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4461 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004462 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004463 synchronized (this) {
4464 nai.networkMonitor.systemReady = mSystemReady;
4465 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004466 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4467 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004468 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004469 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004470 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004471 }
4472
4473 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4474 if (VDBG) log("Got NetworkAgent Messenger");
4475 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004476 synchronized (mNetworkForNetId) {
4477 mNetworkForNetId.put(na.network.netId, na);
4478 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004479 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4480 NetworkInfo networkInfo = na.networkInfo;
4481 na.networkInfo = null;
4482 updateNetworkInfo(na, networkInfo);
4483 }
4484
4485 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4486 LinkProperties newLp = networkAgent.linkProperties;
4487 int netId = networkAgent.network.netId;
4488
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004489 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4490 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004491 if (networkAgent.clatd != null) {
4492 networkAgent.clatd.fixupLinkProperties(oldLp);
4493 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004494
Paul Jensen992f2522014-04-28 10:33:11 -04004495 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 updateMtu(newLp, oldLp);
4497 // TODO - figure out what to do for clat
4498// for (LinkProperties lp : newLp.getStackedLinks()) {
4499// updateMtu(lp, null);
4500// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004501 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004502
Erik Kline94887872016-04-05 13:30:49 +09004503 updateRoutes(newLp, oldLp, netId);
4504 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004505
Paul Jensen3b759822014-05-13 11:44:01 -04004506 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004507 if (isDefaultNetwork(networkAgent)) {
4508 handleApplyDefaultProxy(newLp.getHttpProxy());
4509 } else {
4510 updateProxy(newLp, oldLp, networkAgent);
4511 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004512 // TODO - move this check to cover the whole function
4513 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004514 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004515 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4516 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004517
4518 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004519 }
4520
Lorenzo Colitti95439462014-10-09 13:44:48 +09004521 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4522 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4523 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004524
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004525 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004526 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4527 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004528 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004529 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004530 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 }
Paul Jensen992f2522014-04-28 10:33:11 -04004532
4533 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4534 CompareResult<String> interfaceDiff = new CompareResult<String>();
4535 if (oldLp != null) {
4536 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4537 } else if (newLp != null) {
4538 interfaceDiff.added = newLp.getAllInterfaceNames();
4539 }
4540 for (String iface : interfaceDiff.added) {
4541 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004542 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004543 mNetd.addInterfaceToNetwork(iface, netId);
4544 } catch (Exception e) {
4545 loge("Exception adding interface: " + e);
4546 }
4547 }
4548 for (String iface : interfaceDiff.removed) {
4549 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004550 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004551 mNetd.removeInterfaceFromNetwork(iface, netId);
4552 } catch (Exception e) {
4553 loge("Exception removing interface: " + e);
4554 }
4555 }
4556 }
4557
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004558 /**
4559 * Have netd update routes from oldLp to newLp.
4560 * @return true if routes changed between oldLp and newLp
4561 */
4562 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4564 if (oldLp != null) {
4565 routeDiff = oldLp.compareAllRoutes(newLp);
4566 } else if (newLp != null) {
4567 routeDiff.added = newLp.getAllRoutes();
4568 }
4569
4570 // add routes before removing old in case it helps with continuous connectivity
4571
4572 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4573 for (RouteInfo route : routeDiff.added) {
4574 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004575 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004576 try {
4577 mNetd.addRoute(netId, route);
4578 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004579 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4580 loge("Exception in addRoute for non-gateway: " + e);
4581 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
4583 }
4584 for (RouteInfo route : routeDiff.added) {
4585 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004586 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 try {
4588 mNetd.addRoute(netId, route);
4589 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004590 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4591 loge("Exception in addRoute for gateway: " + e);
4592 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 }
4594 }
4595
4596 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004597 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004598 try {
4599 mNetd.removeRoute(netId, route);
4600 } catch (Exception e) {
4601 loge("Exception in removeRoute: " + e);
4602 }
4603 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004604 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004605 }
Erik Kline41368502015-06-17 13:19:54 +09004606
Erik Kline94887872016-04-05 13:30:49 +09004607 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4608 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4609 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004610 }
Erik Kline94887872016-04-05 13:30:49 +09004611
4612 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004613 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004614 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004615 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004616 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4617 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004618 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004619 }
Erik Kline94887872016-04-05 13:30:49 +09004620 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004621 }
4622
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004623 private String getNetworkPermission(NetworkCapabilities nc) {
4624 // TODO: make these permission strings AIDL constants instead.
4625 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4626 return NetworkManagementService.PERMISSION_SYSTEM;
4627 }
4628 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4629 return NetworkManagementService.PERMISSION_NETWORK;
4630 }
4631 return null;
4632 }
4633
Paul Jensen3d194ea2015-06-16 14:27:36 -04004634 /**
4635 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4636 * augmented with any stateful capabilities implied from {@code networkAgent}
4637 * (e.g., validated status and captive portal status).
4638 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004639 * @param oldScore score of the network before any of the changes that prompted us
4640 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004641 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004642 * @param networkCapabilities the new network capabilities.
4643 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004644 private void updateCapabilities(
4645 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004646 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4647 networkCapabilities)) {
4648 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4649 + nai.networkCapabilities + " -> " + networkCapabilities);
4650 }
4651
Paul Jensen3d194ea2015-06-16 14:27:36 -04004652 // Don't modify caller's NetworkCapabilities.
4653 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004654 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004655 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4656 } else {
4657 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4658 }
Paul Jensene0988542015-06-25 15:30:08 -04004659 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004660 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4661 } else {
4662 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4663 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004664 if (nai.isBackgroundNetwork()) {
4665 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4666 } else {
4667 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4668 }
4669
4670 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4671
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004672 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4673 final String newPermission = getNetworkPermission(networkCapabilities);
4674 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004675 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004676 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004677 } catch (RemoteException e) {
4678 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004679 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004680 }
4681
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004682 final NetworkCapabilities prevNc = nai.networkCapabilities;
4683 synchronized (nai) {
4684 nai.networkCapabilities = networkCapabilities;
4685 }
4686 if (nai.getCurrentScore() == oldScore &&
4687 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4688 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4689 // the change we're processing can't affect any requests, it can only affect the listens
4690 // on this network. We might have been called by rematchNetworkAndRequests when a
4691 // network changed foreground state.
4692 processListenRequests(nai, true);
4693 } else {
4694 // If the requestable capabilities have changed or the score changed, we can't have been
4695 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004696 rematchAllNetworksAndRequests(nai, oldScore);
4697 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004698 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 }
4700
Paul Jensenc8b9a742014-09-30 15:37:41 -04004701 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004702 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4703 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004704 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004705 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004706 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4707 }
4708 }
4709
Robert Greenwalt7b816022014-04-18 15:25:25 -07004710 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4711 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004712 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004713 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4714 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004715 }
4716 }
4717
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004718 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4719 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004720 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004721 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004722 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4723 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004724 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004725 sendIntent(nri.mPendingIntent, intent);
4726 }
4727 // else not handled
4728 }
4729
4730 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4731 mPendingIntentWakeLock.acquire();
4732 try {
4733 if (DBG) log("Sending " + pendingIntent);
4734 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4735 } catch (PendingIntent.CanceledException e) {
4736 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4737 mPendingIntentWakeLock.release();
4738 releasePendingNetworkRequest(pendingIntent);
4739 }
4740 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4741 }
4742
4743 @Override
4744 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4745 String resultData, Bundle resultExtras) {
4746 if (DBG) log("Finished sending " + pendingIntent);
4747 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004748 // Release with a delay so the receiving client has an opportunity to put in its
4749 // own request.
4750 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004751 }
4752
Robert Greenwalt9258c642014-03-26 16:47:06 -07004753 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004754 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004756 Bundle bundle = new Bundle();
4757 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4758 new NetworkRequest(nri.request));
4759 Message msg = Message.obtain();
4760 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4761 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4762 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4763 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004764 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004765 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004766 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004767 break;
4768 }
4769 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4770 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4771 new NetworkCapabilities(networkAgent.networkCapabilities));
4772 break;
4773 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004774 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004775 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4776 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004777 break;
4778 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004779 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004780 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004781 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004782 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004783 if (VDBG) {
4784 log("sending notification " + notifyTypeToName(notificationType) +
4785 " for " + nri.request);
4786 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004787 nri.messenger.send(msg);
4788 } catch (RemoteException e) {
4789 // may occur naturally in the race of binder death.
4790 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4791 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 }
4793
Paul Jensenc8b9a742014-09-30 15:37:41 -04004794 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004795 if (nai.numRequestNetworkRequests() != 0) {
4796 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4797 NetworkRequest nr = nai.requestAt(i);
4798 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004799 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004800 loge("Dead network still had at least " + nr);
4801 break;
4802 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004803 }
4804 nai.asyncChannel.disconnect();
4805 }
4806
Robert Greenwalt7b816022014-04-18 15:25:25 -07004807 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4808 if (oldNetwork == null) {
4809 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4810 return;
4811 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004812 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004813
4814 // If we get here it means that the last linger timeout for this network expired. So there
4815 // must be no other active linger timers, and we must stop lingering.
4816 oldNetwork.clearLingerState();
4817
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004818 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004820 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004821 } else {
4822 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004823 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4824 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004825 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004826 }
4827
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004828 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004829 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004830 setupDataActivityTracking(newNetwork);
4831 try {
4832 mNetd.setDefaultNetId(newNetwork.network.netId);
4833 } catch (Exception e) {
4834 loge("Exception setting default network :" + e);
4835 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004836 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004837 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004838 updateTcpBufferSizes(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004839 }
4840
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004841 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004842 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4843 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4844 NetworkRequest nr = nri.request;
4845 if (!nr.isListen()) continue;
4846 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4847 nai.removeRequest(nri.request.requestId);
4848 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4849 }
4850 }
4851
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004852 if (capabilitiesChanged) {
4853 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4854 }
4855
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004856 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4857 NetworkRequest nr = nri.request;
4858 if (!nr.isListen()) continue;
4859 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4860 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004861 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004862 }
4863 }
4864 }
4865
Paul Jensen2161a8e2014-09-11 11:00:39 -04004866 // Handles a network appearing or improving its score.
4867 //
4868 // - Evaluates all current NetworkRequests that can be
4869 // satisfied by newNetwork, and reassigns to newNetwork
4870 // any such requests for which newNetwork is the best.
4871 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004872 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004873 // needed. A network is needed if it is the best network for
4874 // one or more NetworkRequests, or if it is a VPN.
4875 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004876 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004877 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004878 //
4879 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4880 // networks that have no chance (i.e. even if validated)
4881 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004882 //
4883 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4884 // it does not remove NetworkRequests that other Networks could better satisfy.
4885 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4886 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4887 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004888 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004889 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004890 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4891 // performed to tear down unvalidated networks that have no chance (i.e. even if
4892 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004893 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004894 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004895 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004896 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004897 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004898 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004899
4900 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4901 final int score = newNetwork.getCurrentScore();
4902
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004903 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004904
Paul Jensen2161a8e2014-09-11 11:00:39 -04004905 // Find and migrate to this Network any NetworkRequests for
4906 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004907 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004908 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004909 NetworkCapabilities nc = newNetwork.networkCapabilities;
4910 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004911 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004912 // Process requests in the first pass and listens in the second pass. This allows us to
4913 // change a network's capabilities depending on which requests it has. This is only
4914 // correct if the change in capabilities doesn't affect whether the network satisfies
4915 // requests or not, and doesn't affect the network's score.
4916 if (nri.request.isListen()) continue;
4917
Paul Jensencf4c2c62015-07-01 14:16:32 -04004918 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4919 final boolean satisfies = newNetwork.satisfies(nri.request);
4920 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004921 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004922 log("Network " + newNetwork.name() + " was already satisfying" +
4923 " request " + nri.request.requestId + ". No change.");
4924 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004925 keep = true;
4926 continue;
4927 }
4928
4929 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004931 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004932 // next check if it's better than any current network we're using for
4933 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 if (VDBG) {
4935 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004936 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004937 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004939 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004940 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004942 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004943 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004944 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004945 affectedNetworks.add(currentNetwork);
4946 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004947 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004949 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004950 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004951 if (!newNetwork.addRequest(nri.request)) {
4952 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4953 }
4954 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004956 // Tell NetworkFactories about the new score, so they can stop
4957 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 // TODO - this could get expensive if we have alot of requests for this
4959 // network. Think about if there is a way to reduce this. Push
4960 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004961 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004962 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004963 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004964 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004965 if (currentNetwork != null) {
4966 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4967 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 }
4969 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004970 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004971 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4972 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004973 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004974 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4975 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4976 // This means this code doesn't have to handle the case where "currentNetwork" no
4977 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4978 if (DBG) {
4979 log("Network " + newNetwork.name() + " stopped satisfying" +
4980 " request " + nri.request.requestId);
4981 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004982 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004983 if (currentNetwork == newNetwork) {
4984 mNetworkForRequestId.remove(nri.request.requestId);
4985 sendUpdatedScoreToFactories(nri.request, 0);
4986 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004987 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4988 newNetwork.name() +
4989 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004990 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004991 // TODO: Technically, sending CALLBACK_LOST here is
4992 // incorrect if there is a replacement network currently
4993 // connected that can satisfy nri, which is a request
4994 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004995 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4996 // so this code is only incorrect for a network that loses
4997 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004998 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004999 }
5000 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005001 if (isNewDefault) {
5002 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005003 makeDefault(newNetwork);
5004 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
5005 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005006 synchronized (ConnectivityService.this) {
5007 // have a new default network, release the transition wakelock in
5008 // a second if it's held. The second pause is to allow apps
5009 // to reconnect over the new network
5010 if (mNetTransitionWakeLock.isHeld()) {
5011 mHandler.sendMessageDelayed(mHandler.obtainMessage(
5012 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5013 mNetTransitionWakeLockSerialNumber, 0),
5014 1000);
5015 }
5016 }
5017 }
5018
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005019 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5020 Slog.wtf(TAG, String.format(
5021 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5022 nc, newNetwork.networkCapabilities));
5023 }
5024 if (newNetwork.getCurrentScore() != score) {
5025 Slog.wtf(TAG, String.format(
5026 "BUG: %s changed score during rematch: %d -> %d",
5027 score, newNetwork.getCurrentScore()));
5028 }
5029
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005030 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005031 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5032 // If the network went from background to foreground or vice versa, we need to update
5033 // its foreground state. It is safe to do this after rematching the requests because
5034 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5035 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005036 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005037 } else {
5038 processListenRequests(newNetwork, false);
5039 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005040
Paul Jensencf4c2c62015-07-01 14:16:32 -04005041 // do this after the default net is switched, but
5042 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005043 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005044
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005045 // Linger any networks that are no longer needed. This should be done after sending the
5046 // available callback for newNetwork.
5047 for (NetworkAgentInfo nai : affectedNetworks) {
5048 updateLingerState(nai, now);
5049 }
5050 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5051 // does not need to be done in any particular order.
5052 updateLingerState(newNetwork, now);
5053
Paul Jensencf4c2c62015-07-01 14:16:32 -04005054 if (isNewDefault) {
5055 // Maintain the illusion: since the legacy API only
5056 // understands one network at a time, we must pretend
5057 // that the current default network disconnected before
5058 // the new one connected.
5059 if (oldDefaultNetwork != null) {
5060 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5061 oldDefaultNetwork, true);
5062 }
5063 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5064 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5065 notifyLockdownVpn(newNetwork);
5066 }
5067
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005069 // Notify battery stats service about this network, both the normal
5070 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005071 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005072 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005073 final IBatteryStats bs = BatteryStatsService.getService();
5074 final int type = newNetwork.networkInfo.getType();
5075
5076 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5077 bs.noteNetworkInterfaceType(baseIface, type);
5078 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5079 final String stackedIface = stacked.getInterfaceName();
5080 bs.noteNetworkInterfaceType(stackedIface, type);
5081 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5082 }
5083 } catch (RemoteException ignored) {
5084 }
5085
Robert Greenwalt152ed372014-12-17 17:19:53 -08005086 // This has to happen after the notifyNetworkCallbacks as that tickles each
5087 // ConnectivityManager instance so that legacy requests correctly bind dns
5088 // requests to this network. The legacy users are listening for this bcast
5089 // and will generally do a dns request so they can ensureRouteToHost and if
5090 // they do that before the callbacks happen they'll use the default network.
5091 //
5092 // TODO: Is there still a race here? We send the broadcast
5093 // after sending the callback, but if the app can receive the
5094 // broadcast before the callback, it might still break.
5095 //
5096 // This *does* introduce a race where if the user uses the new api
5097 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5098 // they may get old info. Reverse this after the old startUsing api is removed.
5099 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005100 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5101 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005102 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005103 // legacy type tracker filters out repeat adds
5104 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5105 }
5106 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005107
5108 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5109 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5110 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5111 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5112 if (newNetwork.isVPN()) {
5113 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5114 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005116 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5117 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005118 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005119 if (nai.getLingerExpiry() > 0) {
5120 // This network has active linger timers and no requests, but is not
5121 // lingering. Linger it.
5122 //
5123 // One way (the only way?) this can happen if this network is unvalidated
5124 // and became unneeded due to another network improving its score to the
5125 // point where this network will no longer be able to satisfy any requests
5126 // even if it validates.
5127 updateLingerState(nai, now);
5128 } else {
5129 if (DBG) log("Reaping " + nai.name());
5130 teardownUnneededNetwork(nai);
5131 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005132 }
5133 }
5134 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005135 }
5136
Paul Jensen1c7ba022015-06-16 14:27:36 -04005137 /**
5138 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5139 * being disconnected.
5140 * @param changed If only one Network's score or capabilities have been modified since the last
5141 * time this function was called, pass this Network in this argument, otherwise pass
5142 * null.
5143 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5144 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5145 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5146 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5147 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005148 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005149 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005150 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5151 // to avoid the slowness. It is not simply enough to process just "changed", for
5152 // example in the case where "changed"'s score decreases and another network should begin
5153 // satifying a NetworkRequest that "changed" currently satisfies.
5154
5155 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5156 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5157 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005158 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005159 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005160 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005161 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005162 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5163 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5164 // Rematch higher scoring networks first to prevent requests first matching a lower
5165 // scoring network and then a higher scoring network, which could produce multiple
5166 // callbacks and inadvertently unlinger networks.
5167 Arrays.sort(nais);
5168 for (NetworkAgentInfo nai : nais) {
5169 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005170 // Only reap the last time through the loop. Reaping before all rematching
5171 // is complete could incorrectly teardown a network that hasn't yet been
5172 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005173 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005174 : ReapUnvalidatedNetworks.REAP,
5175 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005176 }
5177 }
5178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005179
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005180 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005181 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005182 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005183 // For now only update icons for default connection.
5184 // TODO: Update WiFi and cellular icons separately. b/17237507
5185 if (!isDefaultNetwork(nai)) return;
5186
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005187 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005188 // Don't repeat publish.
5189 if (newInetCondition == mDefaultInetConditionPublished) return;
5190
5191 mDefaultInetConditionPublished = newInetCondition;
5192 sendInetConditionBroadcast(nai.networkInfo);
5193 }
5194
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005195 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5196 if (mLockdownTracker != null) {
5197 if (nai != null && nai.isVPN()) {
5198 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5199 } else {
5200 mLockdownTracker.onNetworkInfoChanged();
5201 }
5202 }
5203 }
5204
Robert Greenwalt7b816022014-04-18 15:25:25 -07005205 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005206 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005207 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005208 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005209 synchronized (networkAgent) {
5210 oldInfo = networkAgent.networkInfo;
5211 networkAgent.networkInfo = newInfo;
5212 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005213 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005214
5215 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005216 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5217 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5218 notifyIfacesChangedForNetworkStats();
5219 } else if (VDBG) log("ignoring duplicate network state non-change");
5220 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005221 return;
5222 }
5223 if (DBG) {
5224 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5225 (oldInfo == null ? "null" : oldInfo.getState()) +
5226 " to " + state);
5227 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005228
Robin Lee585e2482016-05-01 23:00:00 +01005229 if (!networkAgent.created
5230 && (state == NetworkInfo.State.CONNECTED
5231 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005232
5233 // A network that has just connected has zero requests and is thus a foreground network.
5234 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5235
Robert Greenwalt7b816022014-04-18 15:25:25 -07005236 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005237 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005238 if (networkAgent.isVPN()) {
5239 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005240 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5241 (networkAgent.networkMisc == null ||
5242 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005243 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005244 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005245 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005246 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005248 loge("Error creating network " + networkAgent.network.netId + ": "
5249 + e.getMessage());
5250 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005251 }
Paul Jenseneec75412014-08-04 12:21:19 -04005252 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005253 }
5254
5255 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5256 networkAgent.everConnected = true;
5257
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005259 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005260
Paul Jensenca8f16a2014-05-09 12:47:55 -04005261 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005262 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005263
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005264 if (networkAgent.isVPN()) {
5265 // Temporarily disable the default proxy (not global).
5266 synchronized (mProxyLock) {
5267 if (!mDefaultProxyDisabled) {
5268 mDefaultProxyDisabled = true;
5269 if (mGlobalProxy == null && mDefaultProxy != null) {
5270 sendProxyBroadcast(null);
5271 }
5272 }
5273 }
5274 // TODO: support proxy per network.
5275 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005276
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005277 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5278 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5279 // capabilities, so it only needs to be done once on initial connect, not every time the
5280 // network's capabilities change. Note that we do this before rematching the network,
5281 // so we could decide to tear it down immediately afterwards. That's fine though - on
5282 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5283 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005284 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005285
Paul Jensen2161a8e2014-09-11 11:00:39 -04005286 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005287 final long now = SystemClock.elapsedRealtime();
5288 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005289
5290 // This has to happen after matching the requests, because callbacks are just requests.
5291 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005292 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005293 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005294 if (networkAgent.isVPN()) {
5295 synchronized (mProxyLock) {
5296 if (mDefaultProxyDisabled) {
5297 mDefaultProxyDisabled = false;
5298 if (mGlobalProxy == null && mDefaultProxy != null) {
5299 sendProxyBroadcast(mDefaultProxy);
5300 }
5301 }
5302 }
5303 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005304 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5305 state == NetworkInfo.State.SUSPENDED) {
5306 // going into or coming out of SUSPEND: rescore and notify
5307 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005308 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005309 }
5310 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5311 ConnectivityManager.CALLBACK_SUSPENDED :
5312 ConnectivityManager.CALLBACK_RESUMED));
5313 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005314 }
5315 }
5316
Robert Greenwaltac96c522014-06-03 16:43:57 -07005317 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005318 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005319 if (score < 0) {
5320 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5321 "). Bumping score to min of 0");
5322 score = 0;
5323 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005324
Paul Jensen2161a8e2014-09-11 11:00:39 -04005325 final int oldScore = nai.getCurrentScore();
5326 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005327
Paul Jensen85cf78e2015-06-25 13:25:07 -04005328 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005329
Paul Jensenc8b9a742014-09-30 15:37:41 -04005330 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005331 }
5332
Erik Klinec75d4fa2017-02-15 19:59:17 +09005333 // Notify only this one new request of the current state. Transfer all the
5334 // current state by calling NetworkCapabilities and LinkProperties callbacks
5335 // so that callers can be guaranteed to have as close to atomicity in state
5336 // transfer as can be supported by this current API.
5337 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005338 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005339 if (nri.mPendingIntent != null) {
5340 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5341 // Attempt no subsequent state pushes where intents are involved.
5342 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005343 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005344
5345 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5346 // Whether a network is currently suspended is also an important
5347 // element of state to be transferred (it would not otherwise be
5348 // delivered by any currently available mechanism).
5349 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5350 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5351 }
5352 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5353 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005354 }
5355
Robert Greenwalt8d482522015-06-24 13:23:42 -07005356 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005357 // The NetworkInfo we actually send out has no bearing on the real
5358 // state of affairs. For example, if the default connection is mobile,
5359 // and a request for HIPRI has just gone away, we need to pretend that
5360 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5361 // the state to DISCONNECTED, even though the network is of type MOBILE
5362 // and is still connected.
5363 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5364 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005365 if (state != DetailedState.DISCONNECTED) {
5366 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005367 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005368 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005369 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005370 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5371 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5372 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5373 if (info.isFailover()) {
5374 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5375 nai.networkInfo.setFailover(false);
5376 }
5377 if (info.getReason() != null) {
5378 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5379 }
5380 if (info.getExtraInfo() != null) {
5381 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5382 }
5383 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005384 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005385 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005386 if (newDefaultAgent != null) {
5387 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5388 newDefaultAgent.networkInfo);
5389 } else {
5390 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5391 }
5392 }
5393 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5394 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005395 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005396 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005397 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005398 }
5399 }
5400 }
5401
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005402 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005403 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005404 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5405 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005406 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5407 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005408 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5409 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005410 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005411 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005412 } else {
5413 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5414 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005415 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005416 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005417
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005418 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5419 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5420 }
5421
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005422 private String notifyTypeToName(int notifyType) {
5423 switch (notifyType) {
5424 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5425 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5426 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5427 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5428 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5429 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5430 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5431 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5432 }
5433 return "UNKNOWN";
5434 }
5435
Jeff Sharkey69736342014-12-08 14:50:12 -08005436 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005437 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5438 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005439 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005440 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005441 try {
5442 mStatsService.forceUpdateIfaces();
5443 } catch (Exception ignored) {
5444 }
5445 }
5446
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005447 @Override
5448 public boolean addVpnAddress(String address, int prefixLength) {
5449 throwIfLockdownEnabled();
5450 int user = UserHandle.getUserId(Binder.getCallingUid());
5451 synchronized (mVpns) {
5452 return mVpns.get(user).addAddress(address, prefixLength);
5453 }
5454 }
5455
5456 @Override
5457 public boolean removeVpnAddress(String address, int prefixLength) {
5458 throwIfLockdownEnabled();
5459 int user = UserHandle.getUserId(Binder.getCallingUid());
5460 synchronized (mVpns) {
5461 return mVpns.get(user).removeAddress(address, prefixLength);
5462 }
5463 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005464
5465 @Override
5466 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5467 throwIfLockdownEnabled();
5468 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005469 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005470 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005471 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005472 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005473 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005474 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005475 }
5476 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005477 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005478
5479 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005480 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005481 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005482 }
5483
5484 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005485 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5486 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5487 enforceKeepalivePermission();
5488 mKeepaliveTracker.startNattKeepalive(
5489 getNetworkAgentInfoForNetwork(network),
5490 intervalSeconds, messenger, binder,
5491 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5492 }
5493
5494 @Override
5495 public void stopKeepalive(Network network, int slot) {
5496 mHandler.sendMessage(mHandler.obtainMessage(
5497 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5498 }
5499
5500 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005501 public void factoryReset() {
5502 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005503
5504 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5505 return;
5506 }
5507
Robin Lee3b3dd942015-05-12 18:14:58 +01005508 final int userId = UserHandle.getCallingUserId();
5509
Stuart Scottf1fb3972015-04-02 18:00:02 -07005510 // Turn airplane mode off
5511 setAirplaneMode(false);
5512
Stuart Scotte3e314d2015-04-20 14:07:45 -07005513 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5514 // Untether
5515 for (String tether : getTetheredIfaces()) {
5516 untether(tether);
5517 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005518 }
5519
Stuart Scotte3e314d2015-04-20 14:07:45 -07005520 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005521 // Remove always-on package
5522 synchronized (mVpns) {
5523 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5524 if (alwaysOnPackage != null) {
5525 setAlwaysOnVpnPackage(userId, null, false);
5526 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5527 }
5528 }
5529
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005530 // Turn Always-on VPN off
5531 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5532 final long ident = Binder.clearCallingIdentity();
5533 try {
5534 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5535 mLockdownEnabled = false;
5536 setLockdownTracker(null);
5537 } finally {
5538 Binder.restoreCallingIdentity(ident);
5539 }
5540 }
5541
Stuart Scotte3e314d2015-04-20 14:07:45 -07005542 // Turn VPN off
5543 VpnConfig vpnConfig = getVpnConfig(userId);
5544 if (vpnConfig != null) {
5545 if (vpnConfig.legacy) {
5546 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5547 } else {
5548 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5549 // in the future without user intervention.
5550 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005551
Victor Changb04a5ea2016-05-30 20:36:30 +01005552 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005553 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005554 }
5555 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005556
5557 Settings.Global.putString(mContext.getContentResolver(),
5558 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005559 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005560
5561 @VisibleForTesting
5562 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5563 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5564 return new NetworkMonitor(context, handler, nai, defaultRequest);
5565 }
Erik Kline48f12f22016-04-14 17:30:59 +09005566
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005567 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005568 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5569 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005570 }
5571
5572 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005573 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5574 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5575 }
5576
Hugo Benichicfddd682016-05-31 16:28:06 +09005577 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005578 int newNetid = NETID_UNSET;
5579 int prevNetid = NETID_UNSET;
5580 int[] transports = new int[0];
5581 boolean hadIPv4 = false;
5582 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005583
Hugo Benichi5f16f762016-04-20 12:09:33 +09005584 if (newNai != null) {
5585 newNetid = newNai.network.netId;
5586 transports = newNai.networkCapabilities.getTransportTypes();
5587 }
5588 if (prevNai != null) {
5589 prevNetid = prevNai.network.netId;
5590 final LinkProperties lp = prevNai.linkProperties;
5591 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5592 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5593 }
5594
Hugo Benichicfddd682016-05-31 16:28:06 +09005595 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5596 }
5597
5598 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5599 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601}